【问题标题】:Unexpected error:"Dereferencing pointer to incomplete type" with code::blocks, c language意外错误:“取消引用指向不完整类型的指针”,代码::blocks,c 语言
【发布时间】:2014-06-27 15:40:20
【问题描述】:

我正在为我的基本 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 指针作为输入,插入姓名surname 和年龄,创建列表的新元素并返回它的指针。我不明白它有什么问题......我为我的愚蠢道歉。 另一个问题,如果我写input->next=newElement; 而不是*input->next=*newElement;,我不会收到错误,但会收到警告:“分配来自不兼容的指针类型[默认启用]”。再次为我的无能感到抱歉,但我必须问你这是什么意思,两行之间有什么区别。 希望您不介意帮助我,并提前感谢您。

【问题讨论】:

  • …或sizeof *list,如果你想使用变量名而不是类型…并且你的声明中有struct listplot *next而不是struct listPlot *next,这就是你的编译器警告的原因(在你的错误修复之后,这对我来说似乎是正确的)。另请注意,您必须将前一个元素链接到添加的元素(当前,您正在写入未分配的空间)。永远不要使用gets
  • 非常感谢,真的。你的眼睛真是太棒了。我能问你为什么我不应该使用gets吗?

标签: c list pointers linked-list codeblocks


【解决方案1】:
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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多