gpt4 book ai didi

c - 段错误但找不到错误

转载 作者:行者123 更新时间:2023-11-30 20:44:03 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>

struct node {
char str[200];
int nn;
struct node* next;
};

int number;
struct node* start=NULL;
struct node* current;
//function to insert into the list

void insert() {
struct node* n;
n=(struct node*)malloc(sizeof(struct node));
n->str=malloc(sizeof(char) * 1000);
printf("please enter the data that you would like to insert: ");
gets(n->str);
printf("asdasdasdasd");
n->next=NULL;
if( start==NULL ) {
start->next=n;
current=n;
}
else {

current->next=n;
current=n;

}

printf("done\n");
}

void display() {
current=start;
int i=0;
while( current->next!=NULL ) {
printf("node%d= %s\n",++i,current->str);
current=current->next;

}
printf("this the end");
}


int main() {
char c;
int input;

do {
printf("Select from the following options:\n"
"1.Display list\n"
"2.Add to list\n"
"3.delete from list\n");

scanf("%d",&input);
switch (input) {
case 1: display(); break;
case 2: insert(); break;
// case 3: delete(); break;
default : printf("Please select 1 , 2 or 3\n");
}
printf( "would you like to continue?(y/n)\n");
scanf("%s",&c);
} while(c=='y');

return 0;
}

这在插入函数中给了我一个错误,一个段错误!

我尝试过一些事情,但我只是没有得到清晰的图片。我对指针有点弱,实际上很困惑!

请告诉我我做错了什么,帮助我。忘记我的链表逻辑,让它错吧。我只是想知道为什么会发生段错误!

最佳答案

你有很多错误,但你的崩溃是因为你没有分配start

n->next=NULL;
if( start==NULL ) {
start->next=n;
current=n;
}
else {

current->next=n;
current=n;

你询问 start 是否为空,如果是,你尝试通过调用 start->next 来读取它。您需要先分配它。

关于c - 段错误但找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com