【问题标题】:Finding the union type when it has been passed to a function在将联合类型传递给函数时查找联合类型
【发布时间】: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 对象没有 nextXXXX 的成员。
  • 你的结构是什么样的?
  • 你可能需要这样的struct node { enum kind k; Types obj; struct node *next;}
  • 联合所做的只是分配可由其任何组成字段使用的内存。它不知道它包含的实际字段应该是什么。您需要尝试类似@BLUEPIXY 的建议 - 将联合放在结构内,并确保结构的一个字段告诉您该联合包含的类型。

标签: c struct unions


【解决方案1】:

与其他一些语言不同,C 没有在运行时识别对象类型的内置方法。您将识别字符放在结构开头的方法与其他方法一样好。

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2020-08-04
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多