如何解决C - 用字符串创建链表
我有一个存储学生信息的链表。该列表包括一个 char *
和两个 int
,当我尝试用字符串初始化 char *
时出现问题,因为这样做时会出现 Seg Fault。
我尝试过的事情:使用 strcpy
而不是 =
以及动态分配内存。
typedef struct Student{
int age,id;
char *name;
struct Student *next;
}Student;
struct Student *head = NULL;
创建链表函数
Student *create (){
char name[128];
Student *newStudent = (Student*)malloc(sizeof(Student));
newStudent->name = malloc(sizeof(Student) + 1);
newStudent->age = (rand() % (35 - 18 + 1)) + 18; // age range of student from 18-35
newStudent->id = rand() % 1000000 + 100000; // 6 digit id
scanf("%127s",name);
strcpy(newStudent->name,name);
newStudent->next = NULL;
return newStudent;
}
插入函数
Student *insert(Student *newStudent){
Student *ptr = head;
if (head == NULL)
return newStudent;
while (ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = newStudent;
return head;
}
构建函数
Student *build(){
int size;
Student *newStudent = (Student*)malloc(sizeof(Student));
printf("Enter size of linked list: ");
scanf("%d",&size);
for (int i=0; i<size; i++){
newStudent = create();
head = insert(newStudent);
}
return head;
}
打印和主函数
void print(Student *head){
for (Student *ptr = head; ptr != NULL; ptr = ptr->next)
printf("Student info\nName: %s,ID: %d,age: %d\n",ptr->name,ptr->id,ptr->age);
printf("\n");
}
int main(){
srand(time(0));
head = build();
print(head);
return 0;
}
解决方法
char *name; strlen(name);
是未定义的行为,段错误是合理的期望。 char *name; scanf("%s",name);
在这两种情况下,name
都未初始化(因此您可以将其视为无处寻址。)当您尝试计算字符串的长度时,会出现错误。同样,当您尝试使用 scanf
将一些数据写入任何地方时。也许你想要:
char name[128]; scanf("%127s",name);
或类似的。无论您做什么,在使用之前都需要 name
来引用有效的内存位置。是将其声明为数组还是将其声明为指针并使用 malloc
为其分配地址并不重要。 (将其设为数组通常更容易,因为您无需担心free
对其进行处理。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。