2015-02-08 106 views
-1

需要帮助将姓名和身份证号码插入列表中。每当崩溃尝试 添加数量为列表链接列表:插入姓名和身份证号码列表

struct node { 

int id; 
char name[50]; 
struct node *next; 
} *head; 


struct node *insert(struct node * list, char nam[50], int id){ 

struct node *helper; 
struct node *pNew; 
pNew=(struct node*)malloc(sizeof(struct node)); 

strcpy(pNew->name, nam); 
pNew->id = id; 
pNew->next=NULL; 

helper=list; 

if (list == NULL) 
    return pNew; 

while (helper->next!=NULL) 
    helper=helper->next; 

helper->next=pNew; 


return list; 

}

int main() 
{ 

char nameInsert[50]; 
char nameDelete[50]; 
int idNum, i; 
struct node *n=NULL; 

//beginning of linked list, must initialize 
head = NULL; 

//read in data using file input function 
readDataFile(); 

//display data operations using while loop 
while(1) 
{ 
    printf("\nData Operations\n"); 
    printf("\n--------------\n"); 
    printf("1. Insert Name\n"); 
    printf("2. Display Names\n"); 
    printf("3. Delete by ID Number\n"); 
    printf("4. Delete by Name\n"); 
    printf("5. Exit\n"); 
    printf("Please enter a command: "); 

    if(scanf("%d", &i) <= 0) 
    { 
     printf("Not valid input, please use integers 1 - 5"); 
     exit(0); 
    } 
    else 
    { 
     //beginning of switch case 
     switch(i) 
     { 
      case 1: 
       printf("Enter the name you would like to insert: "); 
       scanf("%s",nameInsert); 
       printf("Enter the ID number associated with the name: "); 
       scanf("%d", &idNum); 
       insert(n,nameInsert, idNum); //insert function 
       break; 

应用程序读取数据文件并存储数据作为一个链表。 提示用户输入学生的namePrompt用户为学生的ID numberPopulate与dataAdd链表节点的实例的新节点添加到现有的链接列表

+0

请不要强制'malloc()'和家族的返回值。 – 2015-02-08 20:57:53

+0

请告诉我们'pNew-> name'是否分配内存。 'name'是一个char *'吗? – 2015-02-08 20:59:34

+0

请向我们展示'struct node'的定义, – 2015-02-08 21:01:22

回答

0

我已经简化和修改您的insert()功能

struct node *insert(struct node * list, char *nam, int id){ 
    struct node *pNew; 
    pNew=malloc(sizeof(struct node)); 
    if (pNew == NULL) { 
     printf ("Unable to allocate memory\n") 
     exit (1); 
    } 
    strncpy(pNew->name, nam, 49);  // limit the string copy length 
    pNew->name[49] = 0;     // precautionary terminator 
    pNew->id = id; 
    pNew->next = list;     // point to list passed 
    return pNew;      // return new list 
} 

而你调用insert()的方式会忽略它的返回值,这是新的头部/根目录。

n = insert(n, nameInsert, idNum); // use the return value