我最近开始学习链表,我想知道关于我的代码的两件事:
为什么程序会崩溃?
为什么它在每个成员的末尾都加上一个换行符
\n
?
这是我的代码。我只是想添加一个成员并打印出来。
struct node
{
char* day;
char* month;
char* year;
struct node* next;
};
typedef struct node node;
void print(node* head){
node* temp=head;
while(temp != NULL){
printf("%s %s %s",temp->day,temp->month,temp->year);
temp=temp->next;
}
}
node* add(node* head)
{
node * new_node;
int n;
char temp[25];
new_node = malloc(sizeof(node));
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->day=malloc(n+1);
strcpy(new_node->day,temp);
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->month=malloc(n+1);
strcpy(new_node->month,temp);
fgets(temp,sizeof(temp),stdin);
n=strlen(temp);
new_node->year=malloc(n+1);
strcpy(new_node->year,temp);
new_node->next=head;
return new_node;
}
int main(void)
{
node* head=NULL;
head=malloc(sizeof(node));
if (head == NULL)
{
return 1;
}
head=add(head);
print(head);
return 100;
}
谁能指出我做错了什么以及我本可以做得更好的地方?
最佳答案
当你做一个
ptr = malloc(sizeof(node));
内存已分配但未初始化。这将导致节点结构的下一个指针指向未定义的内容。然后,当您在打印功能中使用它时,程序会崩溃。
放一个
memset(ptr, 0, sizeof(node))
在 malloc 之后或将 next 指针显式初始化为 NULL。
关于c - 理解 C 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640930/