2013-05-25 38 views
0

我想要做c中的人链接列表。 我的所有方法都在main()中工作,直到我将它们放入while循环(用于从用户读取命令)。一切都编译完成,但是当我尝试运行它时,它会崩溃返回随机值。 以下是我的部分代码。在纯c清单实施中需要帮助

结构:

struct Person{ 
      const char* name; 
      const char* sex; 
      int age; 
      struct Person* next; 
} *head; 

方法Insert:

void insert(struct Person* h, char*n, char* s, int a){ 

    for(; h->next != NULL; h=h->next){} 

    struct Person* p = (struct Person*) malloc(sizeof(struct Person)); 
    p->name=n; 
    p->age=a; 
    p->sex=s; 
    p->next=NULL; 
    h->next=p; 
} 

,并主要在它不起作用:

int main() 
{ 
    struct Person Maciek={"Maciek", "Male", 20, NULL}; 
    head = &Maciek; 
    int comand = 0; 


    while(comand != 6){ 
     printf("Choose command:\n 1-insert person \n 2-delete by index \n 3-delete by name \n 4-display by index \n 5-print whole list \n 6-exit\n"); 
     scanf("%d", &comand); 
     if(comand == 1){ 
      printf("Name, Gender, Age\n"); 
      char* name; 
      char* sex; 
      int age;    
      scanf("%s, %s, %d", &name, &sex, &age); 
      printf("Name %s, Sex %s, Age %d", name, sex, age); 

      insert(head, name, sex, age); 
     } 

     if(comand == 2){ 
      printf("2\n"); 
     } 

     if(comand == 3){ 
      printf("3\n"); 
     } 

     if(comand == 4){ 
      printf("4\n"); 
     } 

     if(comand == 5){ 
      printf("5\n"); 
     } 

    } 

    return 0; 
} 

我很新的C/C++,和我真的很感激任何帮助。

+0

你试过调试器吗?你不需要在C程序中输入'malloc'的返回值。 –

+0

打开警告设置 - 至少应该获得格式不匹配警告。 –

回答

2
if(comand == 1){ 
     printf("Name, Gender, Age\n"); 
     char* name; 
     char* sex; 
     int age;    
     scanf("%s, %s, %d", &name, &sex, &age); 

这里使用的是悬摆指针(其在存储器中的任何指点),你应该使用malloc分配一些内存或使用字符数组,并作为卡尔Norum时指出,你不应该有&scanf因为你需要提供一些char*而不是char**。你可以做这样的(这个代码很容易受到缓冲区溢出,不要使用在生产代码,可以考虑使用fgets + sscanf):

char name[50]; 
char sex[20]; 
int age = 0; 
scanf("%s, %s, %d", name, sex, &age); 

在你插入功能:

struct Person* p = (struct Person*) malloc(sizeof(struct Person)); 
p->name=n; 
p->age=a; 
p->sex=s; 

你用n替换p-> name,而不是将n的内容复制到p-> name中。你想要:

struct Person *p = malloc(sizeof(struct Person)); 
p->name = malloc(strlen(n)+1); 
if(p->name == NULL) { 
    //error handling... 
} 
strcpy(p->name, n); 
p->sex = malloc(strlen(s)+1); 
if(p->sex == NULL) { 
    //error handling... 
} 
strcpy(p->sex, s); 
p->age = a; 
+1

'name'和'age'在'scanf'调用中不应该有'&'。 –

+0

char * name =(char *)malloc(20 * sizeof(char)); char * sex =(char *)malloc(6 * sizeof(char));我已经纠正了这一点,它仍然不起作用,你能再次帮助我吗? – Offa

+0

删除您的scanf呼叫中的&运算符。而且你不需要在C中返回malloc的返回值,只需要在C++中使用。 'char * name = malloc(20 * sizeof(char));' –

1

你正在阅读字符串指针,尚未使用分配的内存进行初始化。