c - union 作为 C 中的结构变量

标签 c pointers structure unions

我有以下结构:

complex_attribute
generic_attribute

我定义了这两者的并集,如下所示:

union union_attribute{
    struct complex_attribute *complex;
    struct generic_attribute *generic;
};

然后我定义了另一个结构来跟踪 union 和与之关联的代码:

struct tagged_attribute{
    int code;
    union union_attribute *attribute;
};

然后,我定义了另一个名为 Disk 的结构,它包含一个指向 tagger_attribute 对象的指针数组:

struct disk {
    struct tagged_attribute *attribute_ptr[100];
}

现在我正尝试像这样访问标记属性的代码:

printf("%i", disk_ptr->attribute_ptr[counter]->code); 

但是我遇到了段错误。我访问结构变量“代码”的方式不正确吗?

这是我尝试访问“代码”的所有相关代码:

struct disk* construct_disk(char* name, char* serial, char* vendor, char* model, int RPM, char *raid_type, int num_args, ...){
    struct disk *disk_ptr;
    disk_ptr = malloc (sizeof (struct disk));

    va_list ap;
    va_start(ap, num_args);
    int counter;
    int incrementer;
    //subattributes is a global variable
    incrementer = subattributes[counter];

    for(counter = 0; counter < num_attributes; counter++, incrementer = subattributes[counter]){
        printf("Counter = %i\n", counter);
        printf("incrementer = %i\n", incrementer);
        if (1){
            printf("Populating generic attribute");
            printf("%i", disk_ptr->attribute_ptr[counter]->code);
            //disk_ptr->attribute_ptr[counter]->code = GENERIC_ATTRIBUTE_TYPE;
            //disk_ptr->attribute_ptr[counter]->attribute->generic = construct_generic_attribute(va_arg(ap, int));
        }else{
            printf("Populating complex attribute");
            //struct generic_attribute* input_to_complex_attribute[incrementer];
            //int stepper;
            //for(stepper = 0; stepper<incrementer; stepper++){
            //  input_to_complex_attribute[stepper] = construct_generic_attribute(va_arg(ap, int));
            //}
            //disk_ptr->attribute_ptr[counter]->code = COMPLEX_ATTRIBUTE_TYPE;
            //disk_ptr->attribute_ptr[counter]->attribute->complex = construct_complex_attribute(5, incrementer, input_to_complex_attribute);
        }
    }

    va_end(ap);
    return disk_ptr;
}

最佳答案

您根本没有访问 code(当然,您应该使用它来检查哪个 union 成员有效)。

您正在访问 attribute_ptr 数组的第 counter 个元素,它是指向 tagged_attribute 的指针并试图取消引用它(使用 ->)。可能没有首先分配该指针(或该数组中的任何其他指针),也没有在分配后初始化内存(您没有显示任何相关信息......未能正确分配可能是您的段错误的原因。)

当然,这假定 disk_ptr 已正确分配和初始化......您没有显示,也可能没有。

如前所述,如果您想要更具体的问题答案,请显示所有相关代码。此外,在启用警告的情况下进行编译,并学习使用诸如 gdb(GNU 调试器)和 valgrind(用于内存问题)之类的工具来调试您的代码。

编辑:现在你已经添加了代码,你已经分配了 disk_ptr 但你从来没有在 attribute_ptr 中分配任何东西,所以它只是指向内存中任意位置的 100 个指针.

关于c - union 作为 C 中的结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062575/

相关文章:

c - 为什么 scanf() 不将 array 和 &array 视为相同的?

C:用于创建 HashMap 以使用链接存储字符串的指针

PHP MVC 结构在哪里放置自己的类

c# - 获取用于内存映射的结构的大小

c - 二次多项式求解器 C

c - 为什么 CC 在标题中看不到我的函数定义?

c - 米斯拉-C : cast literal number

c - 为什么这个c程序输出4?

c - 在函数中使用双指针

c++ - 为什么指针使用 -> 而不是 .?