我正在为我的基本 C 作业制作一个链表程序。 但是,我总是会在 .exe 上遇到强制关闭错误,并在 Ubuntu 上遇到段错误。
我尝试将其分解并重写,但我不知道代码在哪里失败。
非常感谢您的帮助。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char name[20];
int mark;
struct node *next;
};
struct node *addnode(char name[], float mark);
int main(void){
int j = 0;
char StdName[10];
float StdMarks;
struct node *head = NULL;
struct node *curr = NULL;
head = curr = addnode('\0',0.0);
for(j=0; j<3; j++){
printf("\nEnter StdName >>");
printf("\nMarks for %s >>", StdName);
curr -> next = addnode("", 5.5);
curr = curr->next;
}
curr = head -> next;
j = 0;
printf("\nnode\tName\tMarks");
while(curr){
printf("\n%d\t%s\t%5.2f", j++, curr->name, curr->mark);
curr=curr->next;
}
return 0;
}
struct node *addnode(char name[], float mark){
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
strcpy(temp->name,name);
temp->mark=mark;
temp->next=NULL;
return (temp);
}
最佳答案
一些错误:
'\0'
不是char[]
,而是值为0
的char
并且转换为char*
(NULL
指针)。使用""
表示空字符串。编译器应该对此发出警告。使用最高警告级别进行编译,并将警告视为错误(因此您不能忽略它们)。对于gcc
,标志是-Wall -Werror
。StdName
未初始化,也从未填充,但在printf("%s")
调用中使用。
关于c - 简单链表C代码段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13659598/