获得"在初始化器周围缺少大括号"初始化链表时

时间:2018-04-15 05:55:36

标签: c debugging gcc warnings

我正在实现一个链表:其中包含简单的Struture和两个辅助函数,附加到llist的末尾并打印llist。

    typedef struct target{
      char my_target[65];
      int ID;
      struct target *next;
    }target_list;

    void append(target_list *head, char* new_data, int new_int){
  target_list *current = head;
  while (current -> next != NULL){
    current = current -> next;
  }
  current -> next = malloc(sizeof(target_list));
  strcpy(current -> next -> my_target,new_data);
  current -> next -> next = NULL;
  current -> next -> ID = new_int;
}

void print_list(target_list* head){
  target_list* current = head;
  while(current != NULL){
    printf("%d\n",current -> ID);
    printf("%s\n",current -> my_target);
    current = current -> next;
  }
}
    target_list head = {NULL}; 
     while(fgets (str , 1024 , f) > 0){
        char* num_args;
        char my_target[65];
        target_list head = {NULL};   //ERROR!
        int target_id = 0;
        int index_1,index_2;

        num_args = strtok(str," ");
        while (num_args != NULL)
        {
          if (num_args[0] != '\n'){
          append(&head,num_args,target_id);
          printf("the node now is %d\n",target_id);
          target_id++;
        }
          num_args = strtok(NULL," ");
        }
        print_list(&head);
        }

我收到的警告信息如下:

original.c:283:5: warning: missing braces around initializer [-Wmissing-braces]
     target_list head = {NULL}; 
     ^
original.c:283:5: warning: (near initialization for 'head.my_target') [-Wmissing-braces]
original.c:283:5: warning: initialization makes integer from pointer without a cast [enabled by default]
original.c:283:5: warning: (near initialization for 'head.my_target[0]') [enabled by default]

有什么想法吗?我之前已经实现了llist,但从未见过像这样的消息。

1 个答案:

答案 0 :(得分:1)

在语句target_list head中,head普通结构变量而非指针变量,您无法使用NULL进行初始化是(void*)0

你应该注意的事情很少,我只是过滤掉了问题并列出了。

  • head应该是struct pointer类型,而不是普通的struct变量 target_list head = {NULL}应为target_list *head = NULL;
  • 第二次无需像head那样再次声明target_list head = {NULL};它应该只是head = NULL;
  • append()append(head,num_args,target_id);
  • 一样致电print_list(head);

正确检查append()功能。