【问题标题】:getting error while compiling this code编译此代码时出错
【发布时间】:2016-04-29 06:52:47
【问题描述】:

我正在编写代码来创建正确的链接列表。请告知本程序中的错误errors while compiling

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    typedef void* cadtpointer;
    struct cadtlist 
    {
      cadtpointer data;
      struct cadtlist* next;
     }; /* structure*/

     struct cadtlist* cadt_list_init( )
     {
        struct cadtlist * temp, * head,* list;
        int num;
        char *p, s[100];
        printf(" enter the number of nodes to be created");
        while (fgets(s, sizeof(s), stdin)) 
        {
          num = strtol(s, &p, 10);
          if (p == s || *p != '\n') 
            {
                printf("Please enter an integer: ");
            }
          else break;
        } 
        while (num != 0)
        {
         if(NULL != list )
         {
           list->next = cadt_create_list(temp);
            }
         else
        {
          list = cadt_create_list(temp);
          head = list;
        }
        num--;
      }


    }
   struct cadtlist* cadt_create_list(struct cadtlist * list)
   {
    int n;
    char * data;
    struct cadtlist * newnode;
    newnode = ( struct cadtlist *) malloc( sizeof(struct cadtlist));
    if( NULL != newnode )
    {
        printf(" enter the data to be added");
        scanf("%s", data);
        n= cadt_add_list(data,newnode);
        if( 1 == n)
        return newnode; 
    }
    else
    {
        printf(" error while allocating memory");
        exit(1);
    }
   }
   struct cadtlist* cadt_add_list( char* item,struct cadtlist * list) 
  {
   list->data = item;
   if(NULL == list->data)
    {
        return list;
    }
    else
    {
        printf(" error while adding data");
        exit(1);
    }
   } 

 int main()
 {
    struct cadtlist* list1;
    list1 = cadt_list_init();

    return 0;
  }

【问题讨论】:

标签: c


【解决方案1】:

1) - 对这些前向声明使用原型

2) - 你正在传递一个局部变量的地址

char * data; /* Local variable */
struct cadtlist * newnode;
newnode = ( struct cadtlist *) malloc( sizeof(struct cadtlist));
if( NULL != newnode )
{
    printf(" enter the data to be added");
    scanf("%s", data);
    n= cadt_add_list(data,newnode); /* Passing local variable */

并将地址分配给另一个变量

struct cadtlist* cadt_add_list( char* item,struct cadtlist * list) 
{
    list->data = item;

请注意,当您从cadt_create_list() 退出时,data 不再可用(可能包含垃圾)

改成

struct cadtlist* cadt_add_list( char* item,struct cadtlist * list) 
{
    list->data = strdup(item); /* Reserve space for the string */

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2020-12-03
    • 2011-01-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多