我正在编写一个通用函数来创建结构的链接列表。 我崩溃的地方在于循环遍历列表以找到 新节点应该消失,因为我不确定如何确定哪种结构类型 在函数内部使用。
我可以使用一些 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;
}
最佳答案
与其他一些语言不同,C 没有内置的方法来在运行时识别对象类型。您将识别字符放在结构开头的方法与其他方法一样好。
关于c - 当 union 类型被传递给函数时查找 union 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463550/