好吧,我在用 C 编写一个小程序时遇到了一个非常有趣的问题。所以我创建了一个数据结构,它有一个对整数变量的引用。当我打印出数据结构的第一个字段的类型时,我得到了正确的结果,因此它打印出了 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);
输出:
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;
}
最佳答案
好吧,所以我的问题是,在数据构造函数中,我没有重新分配整个事物,而是懒惰了,就像这样:
retval.fields[0] = &x;
事实证明它不太正确,这样它就完美地工作了:
retval.fields[0] = ophoAlloc(1,sizeof(Data));
retval.fields[0][0] = x;
关于c - 包含指向自身的指针的结构,但实际上不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49470699/