c - 取消引用指针错误

标签 c pointers data-structures dereference

<分区>

我正在用 c 语言创建一个队列数据结构。

typedef struct Queue_node{

int value;
struct Queue_Node* next;

};

struct Queue_Node* front = NULL;
struct Queue_Node* R = NULL;

void Enqueue(int x) 
{
    struct Queue_node* temp = (struct Queue_node*)malloc(sizeof(struct  Queue_node*));
    temp->value = x;
    temp->next = NULL;

    if (front == NULL && R == NULL)
    {
       R = temp;
       front = R;
       return;
    }

    R->next = temp;
    R = temp;
}

在第 24 行(R->next = temp),编译器告诉我:

dereferencing pointer to incomplete type 'struct Queue_node'.

我无法访问 R->next after 声明,为什么?

最佳答案

您的代码中有一些问题,首先在执行typedef 时给出别名。

typedef struct Queue_node{
    int value;
    struct Queue_Node* next;
}Queue_node;/*put alias name here */

其次,malloc()内存分配不正确

 struct Queue_node* temp = (struct Queue_node*)malloc(sizeof(struct  Queue_node*));

它应该是(分配等于Queue_node 大小的内存,而不是Queue_node* )

 struct Queue_node* temp = malloc(sizeof(struct  Queue_node)); 

同时避免强制转换 malloc() 结果。见此帖Do I cast the result of malloc?

关于c - 取消引用指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49938754/

相关文章:

c - 我该如何调试这个程序?

c - 打开函数 : how to protect against directory opening?

c - 将条目附加到链表的末尾

ruby 性能 : Multi-key hashes

c - 解析数学表达式

c - BST 节点删除函数在递归调用时失败

c - 我如何声明 MPI_COMM_WORLD 以便我可以在任何地方使用它?

c - 使用 pthread 时如何检查线程是否终止?

C++ : Meaning of const char*const*

c - "Pointer being freed not allocated error"