c - 包含指向自身的指针的结构,但实际上不是

标签 c pointers struct

好吧,我在用 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/

相关文章:

c - 在 C 中传递和返回二维数组

c - 具有分层控制的函数指针使用: xtern/namespace C++

c - 全局指针(链表头)未正确更新

c++ - 结构数组似乎不想工作

C Struct & Strcpy,点运算符是否解析为指针

c - 如何在 C 中接收未命名的结构作为函数参数?

c - 从客户端向服务器发送字符串时只接收到第一个字节

c - 递归期间两个连续函数如何插入堆栈

在 C 中从整数数组创建字符串数组

数组大小为零时的 C++ 内存分配行为