包含指向自身的指针的结构,而实际上并非如此

时间:2018-03-24 22:39:08

标签: c pointers struct

好吧,所以我在用C编写一个小程序时遇到了一个非常有趣的问题。所以我创建了一个Data结构,它有一个引用和Integer变量。当我打印出数据结构的第一个字段的类型时,我得到了正确的结果,因此它打印出Integer。如果我进入函数,它会打印出Identity(这是包装Integer的结构的类型),无论我嵌套多少。

Identity myIdentity = NewIdentity(newInteger(5));
printf("%s\n",(*myIdentity.fields[0]).type); // => This prints Integer

//this is the function :
int matches(Data input, Data template) {
    printf("%s\n",(*input.fields[0]).type); // => This prints Identity 
    printf("%s\n", (*(*input.fields[0]).fields[0]).type); // => This prints Identity too

 //calling it has the result of printing out "Identity" two times
 matches( myIdentity, NewIdentity(newInteger(5));

更新:

好的,所以我不知道发生了什么,但是当我这样说时会发生这种情况:

Identity myIdentity = NewIdentity(newInteger(5));
printf("%s\n",(*myIdentity.fields[0]).type);
printf("%s\n",(*myIdentity.fields[0]).type);
printf("%s\n",(*myIdentity.fields[0]).type);
printf("%s\n",(*myIdentity.fields[0]).type);

out:

Integer
1�I��^H��H���PTL��
1�I��^H��H���PTL��
1�I��^H��H���PTL��

更新:

typedef Data Identity;
typedef Data Integer;
typedef struct Data {
    struct Eval evaluator; //totally irrelevant for us
    char * type; 
    int enumeration;
    struct Data ** fields;
} Data;

Identity NewIdentity(Data x){
    Data retval;
    retval.evaluator = newEval(NULL,0,NULL,0,NULL); //irrelevant part
    retval.type = new_string("Identity"); //here's the type
    retval.enumeration = 0;
    retval.fields = ophoAlloc(2,sizeof(Data)); //basically just a straightup calloc at the moment
    retval.fields[0] = &x;
    retval.fields[1] = NULL;
    return retval;
}

Integer newInteger(int val) {
    Integer retval;
    retval.evaluator = newEval(NULL,0,NULL,0,NULL); //irrelevant
    retval.type = new_string("Integer");
    retval.enumeration = val; 
    retval.fields = NULL; 
    return retval;
}

1 个答案:

答案 0 :(得分:0)

好吧,我的问题是,在数据构造函数中,我没有重新分配整个事情,而是只是懒惰而且是这样的:

retval.fields[0] = &x;

事实证明它不太对劲,这种方式完美无缺:

retval.fields[0] = ophoAlloc(1,sizeof(Data));
    retval.fields[0][0] = x;