c - 段错误但找不到错误

标签 c pointers

#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/

相关文章:

c - 使用 _tprintf 错误地打印出二进制文件

c++ - 在 for 循环中创建的对象具有相同的地址

c - 使用指针未声明的 Sprite 错误

c++ - 在 C++ 中将 unordered_map 与自定义值对象一起使用

c - 如何截去小数点后的值

c - 访问另一个结构内的 'typedef struct with char array'

c - 使用 CreateProcess() 启动进程时出现问题

c - 查找二维 vector 数组中的右上元素

c - C函数中的全局变量和返回多个可变长度数组(指针)

C#:指向 double 的指针