【发布时间】:2014-08-23 15:34:04
【问题描述】:
我正在编写一个通用函数来为结构创建一个链表。 我崩溃的地方是遍历列表以找到 新节点应该去,因为我不确定如何确定哪种结构类型是 在函数内部使用。
我可以使用一些if 来确定结构类型吗?
喜欢
if(ID[0]==?? 考虑到两个结构的 ID 是通用的,但是
第一个字符将确定结构类型。我想那里必须
是使用传递给函数的类型来确定类型的另一种方法。
对不起,如果这看起来很基本,我忽略了一些明显的东西。 任何想法将不胜感激。
typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;
/*these structs have more members, but not relevant for this*/
typedef struct item
{
char itemID[ID_LEN + 1];
ItemTypePtr nextItem;
} ItemType;
typedef struct category
{
char categoryID[ID_LEN + 1];
CategoryTypePtr nextCategory;
ItemTypePtr headItem;
unsigned numItems;
} CategoryType;
typedef union types{
CategoryType cat;
ItemType item;
} Types;
int addNode(Types *type, char *str)
{
Types *new=NULL;
Types *current=NULL;
Types *prev = NULL;
Types *head=NULL;
char *ID;
const char* s ="|";
if((new=malloc(sizeof(Types)))== NULL)
{
fprintf(stderr,"Memory Allocation failure!!\n");
return false;
}
/*get ID from first str token this is uniform to both*/
ID=strtok(str,s);
current = head;
/* Search to find where in insert new list node*/
/*WHERE <XXXX> needs to be replace by cat or item, depending on which type it is*/
while (current != NULL && strcmp(current-><XXXX>->ID, ID)/*<<<---this is where I fall down
the XXXX represents cat or item*/
{
prev = current;
current = current->next;
}
/**
code to populate struct
a function that would be called
depending on Types type
*/
if (prev == NULL)
{
head = new;
}
else
{
prev->next = new;
}
return true;
}
【问题讨论】:
-
缺少太多对理解您的问题至关重要的代码。请阅读MCVE。
-
Types对象没有next和XXXX的成员。 -
你的结构是什么样的?
-
你可能需要这样的
struct node { enum kind k; Types obj; struct node *next;} -
联合所做的只是分配可由其任何组成字段使用的内存。它不知道它包含的实际字段应该是什么。您需要尝试类似@BLUEPIXY 的建议 - 将联合放在结构内,并确保结构的一个字段告诉您该联合包含的类型。