c - 意外错误 :"Dereferencing pointer to incomplete type"with code::blocks,c 语言

标签 c list pointers linked-list codeblocks

我正在为我的基础 c 编程考试做这个练习,我得到这个错误:“取消引用指向不完整类型的指针”,使用 code::blocks。 这是我的代码:

struct listPlot{
char name[25];
char surname[25];
int age;
struct listplot *next;
struct listPlot *prev;
};

struct listPlot *list;

struct listPlot *init(void)
{
    list=malloc(sizeof(list));
    list->next=NULL;
    list->prev=NULL;
    return list;
};

struct listPlot *addElement(struct listPlot *input)
{
    printf("\nNew element, Name:\n");
    gets(input->name);
    printf("\nSurname:\n");
    gets(input->surname);
    printf("\nAge:\n");
    scanf("%d", &input->age);
    struct listPlot *newElement=malloc(sizeof(list));
    *input->next=*newElement; //This is the line where the error occurs
    newElement->next=NULL;
    *newElement->prev=*input;
};

此函数 addElement 应将 listPlot 指针作为输入,插入名称姓氏和年龄,创建列表的新元素并返回它的指针。我不明白它有什么问题......我为我的愚蠢道歉。 另一个问题,如果我写 input->next=newElement; 而不是 *input->next=*newElement; 我没有收到任何错误,但收到警告:“来自不兼容的分配指针类型[默认启用]”。再次为我的无能道歉,但我必须问你那是什么意思,这两行之间有什么区别。 希望您不介意帮助我,在此先感谢您。

最佳答案

struct listPlot{
  char name[25];
  char surname[25];
  int age;
  struct listplot *next;
  struct listPlot *prev;
};

你上面有一个错字。 struct listplot *next 应该是 struct listPlot *next(大写 P)。您的编译器不知道 struct listplot 是什么,因此自然无法取消引用指向它的指针。


list=malloc(sizeof(list));

这是错误的。大小应该是任何 list 指向的大小,而不是 list 本身。您还应该在使用前测试 malloc() 的返回值:

struct listPlot *init(void)
{
  list = malloc (sizeof *list);
  if (list) {
    list->next=NULL;
    list->prev=NULL;
  }
  return list;
}

struct listPlot *addElement(struct listPlot *input)
{
  printf("\nNew element, Name:\n");
  gets(input->name);

gets() 本质上是不安全的,应该(几乎)永远不要使用。如果输入比您预期的要长,它将继续写入您的缓冲区之外。更好的选择是 fgets()


  .... 
  struct listPlot *newElement=malloc(sizeof(list));

尺寸又错了。更好:

  struct listPlot *newElement = malloc(sizeof *newElement);

sizeof 左边的标识符,前面有一个星号,你会自动得到正确的大小(对于一个元素)。读者不需要查找什么是 list


  *input->next=*newElement; //This is the line where the error occurs
  newElement->next=NULL;
  *newElement->prev=*input;

这些行应该是:

  input->next = newElement;
  newElement->next = NULL;
  newElement->prev = input;
}

此外,您在某些函数定义的末尾有分号。是那些错别字吗?我不认为他们会编译。

关于c - 意外错误 :"Dereferencing pointer to incomplete type"with code::blocks,c 语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24455740/

相关文章:

c - 复杂数据类型的 Typedef

c - 为什么在 "free"之后取消引用 C 指针给出值 0

c++ - 通过对对象的引用构造类

python - 每个数字重复的连续数字列表

java - 我根据 xsd 验证 xml 后如何列出所有错误?

c - 效率 : arrays vs pointers

c - 二维实时绘图与 C

python - 当顺序很重要时如何从元组列表中删除重复项

c - 有谁知道为什么我得到 SIGSEGV,执行 0x90 导致段错误

c++ - 配置 Netbeans 以调试包含非标准库的 C++ 程序