【问题标题】:Error while trying to assign incompatible types尝试分配不兼容的类型时出错
【发布时间】:2012-03-26 09:04:18
【问题描述】:

当我尝试打印此列表时遇到的错误是不兼容的类型错误。我尝试将其转换为结构宏、静态结构宏、指针,但都不起作用。

struct macro {
  struct macro *next;
  char * macro_name;
  char * macro_body;
};

static struct macro macro_list = {
  .next = NULL,
  .macro_name = NULL,
  .macro_body = NULL
};

//--------------------------------------------------------------------------------

void macro_list_print(void){
  printf("Printing macro_list\n");
  if(macro_list.next == NULL){
    printf("--No macros\n");
  }
  struct macro p = macro_list;
  while(p.next != NULL){
    printf("%s %s\n",p.macro_name,p.macro_body);
    p = macro_list.next; //This line gives me the error. 
  }
}

我不知道在这里做什么。任何帮助都会被占用,谢谢。

【问题讨论】:

  • 请包括您收到的错误。

标签: c types variable-assignment incompatibility


【解决方案1】:

pstruct macromacro_list.nextstruct macro*。改为:

struct macro* p = &macro_list;
while(p != NULL){
    printf("%s %s\n",p->macro_name,p->macro_body);
    p = p->next;
}

我进行了以下附加更改:

  • macro_list.nextp->next,否则它永远不会超过列表中的第二项。
  • while 中的条件更改为p != NULL,否则它不会处理列表中的最后一个元素,因为它正在检查p->next != NULL

【讨论】:

    【解决方案2】:

    p 的类型为 macro,但 macro_list.next 的类型为 macro *

    我将其定义为struct macro *,而不是将macro_list 定义为struct macro(名称和正文为空)。

    此外,当您浏览列表时,您希望p = p->next; 能够找到列表中的下一项。实际上,您总是分配 macro_list.next,因此您将反复查看列表中的第一项。

    要遍历这样的链表,我通常会使用:

    struct macro *macro_list = NULL;
    
    for (p=macro_list; p!= NULL; p=p->next) 
        printf("%s %s\n", p->macro_name, p->macro_body);
    

    【讨论】:

      【解决方案3】:

      我假设 next 是一个指针,所以:

      void macro_list_print(void){
        printf("Printing macro_list\n");
        if(macro_list.next == NULL){
          printf("--No macros\n");
        }
        struct macro* p = &macro_list;
        while(p->next != NULL){
          printf("%s %s\n",p->macro_name,p->macro_body);
          p = macro_list.next;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多