每当我尝试扫描输入时,例如:JASON BOURNE JULY 5 1972
,程序崩溃。
scanf("%s %s %s %d %d", temp->fname, temp->lname, temp->month, temp->day, temp->year);
我确定它与%d
有关,而如果我提出:
scanf("%s %s %s", temp->fname, temp->lname, temp->month);
scanf("%d %d", temp->month, temp->day);
String
值是正确的,程序在int
被分配之前就崩溃了。
这是我的结构的副本:
typedef struct node{
char fname [29];
char lname [29];
char month [9];
int day;
int year;
struct student * next;
struct student * previous;
} student;
这是main()中我的函数的副本:
student * head = malloc(sizeof(student));
student * temp = head;
int num = numStudents;
while(num != 0){
scanf("%s %s %s %d %d", temp->fname, temp->lname, temp->month, temp->day, temp->year);
printf("FUNCTION NEVER REACHES THIS POINT");
temp = temp->next = malloc(sizeof(student));
num--;
}temp->next = NULL;
答案 0 :(得分:0)
如果有人有兴趣,我会采取以下措施让所有事情发挥作用:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
//Struct for Student
struct student{
char fname [29];
char lname [29];
char month [9];
int day;
int year;
struct student *next;
struct student *previous;
};
//Pre-Call
void printList(struct student *node);
struct student * insertNode(struct student * list, char fname[29], char lname[29], char month[9], int day, int year);
//Main function
int main(){
//Take Input and Assign Variables
int classes, i;
scanf("%d", &classes);
for(i = 0; i < classes; i++){
int numStudents, j;
scanf("%d", &numStudents);
struct student *list = NULL; //Create LL
int num = numStudents, day, year;
char fname[29]; char lname[29]; char month[9];
//Assign Values
while(num != 0){
scanf("%s %s %s %d %d", &fname, &lname, &month, &day, &year);
list = insertNode(list, fname, lname, month, day, year);
num--;
}
//
printList(list);
}
return 0;
}
//Function to insert a node to the LL
struct student * insertNode(struct student * list, char fname[29], char lname[29], char month[9], int day, int year){
//If the list is empty
if(list == NULL){
struct student * tempNode = (struct student *) malloc(sizeof(struct student));
strcpy(tempNode->fname,fname);
strcpy(tempNode->lname,lname);
strcpy(tempNode->month,month);
tempNode->day = day;
tempNode->year = year;
tempNode->next = NULL; // Extremely Important
return tempNode;
}
//If the list has a node
list->next = insertNode(list->next, fname, lname, month, day, year);
return list;
}
//Function to print a LL
void printList(struct student * node){
if(node->next == NULL)
printf("%s %s %s %d %d\n", node->fname, node->lname, node->month, node->day, node->year);
else
{
printf("%s %s %s %d %d\n", node->fname, node->lname, node->month, node->day, node->year);
printList(node->next);
}
}