C 在已传递给函数时查找联合类型
我正在编写一个泛型函数来创建结构的链表。 我崩溃的地方是在列表中循环查找 新节点应该被删除,因为我不确定如何确定是哪种结构类型 从函数内部使用 我是否能够使用一些C 在已传递给函数时查找联合类型,c,struct,unions,C,Struct,Unions,我正在编写一个泛型函数来创建结构的链表。 我崩溃的地方是在列表中循环查找 新节点应该被删除,因为我不确定如何确定是哪种结构类型 从函数内部使用 我是否能够使用一些if来确定结构类型 像 if(ID[0]=??假设两个结构的ID都是公共的,但是 第一个字符将决定结构类型。我认为必须有 是使用传递给函数的类型确定类型的另一种方法 抱歉,如果这看起来很基本,而我忽略了一些明显的东西。 如有任何想法,将不胜感激 typedef struct category* CategoryTypePtr; type
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;
}
typedef结构类别*CategoryTypePtr;
typedef结构项*ItemTypePtr;
/*这些结构有更多的成员,但与此无关*/
typedef结构项
{
char itemID[ID_LEN+1];
ItemTypePtr nextItem;
}项目类型;
类型定义结构类别
{
字符类别ID[ID_LEN+1];
类别类型PTR nextCategory;
项目类型PTR标题项目;
未签名的numItems;
}分类类型;
typedef联合类型{
分类型猫;
项目类型项目;
}类型;
int addNode(类型*type,字符*str)
{
类型*new=NULL;
类型*当前=空;
类型*prev=NULL;
类型*head=NULL;
字符*ID;
常量字符*s=“|”;
if((new=malloc(sizeof(Types)))==NULL)
{
fprintf(stderr,“内存分配失败!!\n”);
返回false;
}
/*从第一个str标记获取ID这对两者都是一致的*/
ID=strtok(str,s);
电流=水头;
/*搜索以查找“插入新列表”节点中的位置*/
/*需要用cat或item替换的位置,取决于其类型*/
while(当前!=NULL&&strcmp(当前->->ID,ID)/* 与其他一些语言不同,C没有在运行时识别对象类型的内置方法。在结构开头添加识别字符的方法与其他方法一样好。缺少太多对理解问题至关重要的代码。请阅读。类型
对象没有nex的成员t
和XXXX
。您的结构是什么样子的?您可能需要这样的结构节点{enum kind k;Types obj;struct node*next;}
union所做的一切就是分配内存,供其任何组成字段使用。它不知道它所包含的实际字段应该是什么。您需要尝试类似@BLUEPIXY的建议的方法-将union放在结构中,并确保结构的一个字段告诉您该un包含的类型离子。