【问题标题】:Is it possible to have all of a specific type of struct reference the same instance of another struct? C是否可以让所有特定类型的结构引用另一个结构的相同实例? C
【发布时间】:2018-11-03 20:22:15
【问题描述】:

我不是有史以来最伟大的 C 程序员,所以这可能是一个愚蠢的问题,但有没有办法让特定结构的所有类型都引用另一个结构的相同结构实例?

这方面的一个例子是:

    #include <stdio.h>
#include <stdlib.h>
int idxgiver;
typedef struct component component_t;
typedef struct componentA componentA_t;
typedef struct componentB componentB_t;

static struct component{
    int idx;
};

struct componentA{
    component_t component;
};

struct componentB{
    component_t component;
};


componentA_t *componentA_init(){

    componentA_t *a = malloc(sizeof(componentA_t));
    if(a->component.idx == 0){
        a->component.idx = idxgiver;
        idxgiver++;
    }
    return a;
}



componentB_t *componentB_init(){

    componentB_t *b = malloc(sizeof(componentB_t));
    if(b->component.idx == 0){
        b->component.idx = idxgiver;
        idxgiver++;
    }
    return b;
}

int main(){

    componentA_t *a = componentA_init();
    componentB_t *b = componentB_init();

    printf("%d\n", a->component.idx);
    printf("%d\n", b->component.idx);

    componentB_t *b2 = componentB_init();
    printf("%d\n", b2->component.idx);

    return 0;
}

此代码的目标是根据每个组件的类型为每个组件赋予其独特的值,因此理想情况下,这段代码的结果是组件 A 获得值 0(它确实如此)。组件 B 得到值 1(它确实如此),组件 B2 也得到值 1(它没有得到 2)?

因此,如果有任何指向此或任何想法的指针,将不胜感激。

【问题讨论】:

  • 你的编译器不抱怨static struct component{ int idx; };吗?
  • 您的代码有未定义的行为。 if(a-&gt;component.idx == 0){ 访问 a-&gt;component.idx,这是未初始化的。
  • 查看这个问题 [和我的回答],因为它可能会有所帮助:stackoverflow.com/questions/52788369/…

标签: c struct static


【解决方案1】:

malloc 返回的内存未初始化。因此,当您使用 malloc 为结构分配空间时:

componentA_t *a = malloc(sizeof(componentA_t));

然后检查该结构的字段:

if(a->component.idx == 0){

您正在读取一个未初始化的值。所以它可以是 0 或任何其他值。

不需要这个检查,所以删除它:

componentA_t *componentA_init(){
    componentA_t *a = malloc(sizeof(componentA_t));
    a->component.idx = idxgiver;
    idxgiver++;
    return a;
}

componentB_t *componentB_init(){
    componentB_t *b = malloc(sizeof(componentB_t));
    b->component.idx = idxgiver;
    idxgiver++;
    return b;
}

还要注意idxgiver 没有显式初始化,但由于它是在文件范围内定义的,所以它被隐式初始化为 0。

【讨论】:

  • 确实不需要a-&gt;component.idx == 0,但if(a){a-&gt;component.idx = idxgiver; 之前会有用。
【解决方案2】:

int idxgiver 在全局范围内。代码可以正常工作。如果您希望componentA_tcomponentB_t 具有不同的idxgivers,那么通过定义两个idxgivers 来实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-20
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多