c - 指针明显无缘无故地改变 - C

标签 c list function pointers

我的学校作业是用 C 语言创建一个数据库,我可以从文件或键盘中读取数据,但数据库本身存储在内存中。

现在,我不会直接在作业上寻求帮助,但由于我是 C 语言新手,我不明白为什么我编写的这段代码不起作用。

源文件的一部分,应该将学生添加到链接列表中。

想在这里添加这些,我确实将初始值设置为 NULL。


struct student *student_root = NULL;
struct teacher *teacher_root = NULL;

    void add_student(char *name) {
    if (student_root == NULL) { //if there is no student in the list

        /* Allocate memory equivalent to the size of struct student
        and store the address in student_root */
        student_root = malloc(sizeof(struct student));
        // ^ this is something I tried to do to fix it, but I think it is not needed

        struct student new; //creating the student root
        inn_student(&new); //innitializing the root
        student_root = &new;
        set_sn(student_root, 1);//sn = student number, like an ID
        set_student_name(student_root, name);

        student_out(*student_root);this works here
    }
    else {
        struct student new; //creating the student that is to be added
        inn_student(&new); //innitializing the student that is to be added

        set_student_name(&new, name);

        printf("%d\n", student_root->student_number);//when I do this, I get a random number instead of '1'
        set_next_student(student_root, &new); // adding the new student to the list (student number is added automatically)
    }
}

我面临的问题是,第一次插入时,student_root 指针正在工作,它指向"new"学生结构。 。 。但是当我添加其他东西时,它就不起作用了。函数完成后,"new"结构是否会被遗忘在内存中?如果是这样,如何解决?

最佳答案

student_root = malloc(sizeof(struct student));

struct student new; //creating the student root
inn_student(&new); //innitializing the root
student_root = &new;

在初始化student_root以指向堆位置后,再往下几行将其再次设置为指向一个自动局部变量,当您从此返回时,该变量的内存将被其他代码重写功能。

正确的做法是初始化inn_student(student_root)的字段,而不是inn_student(&new)

关于c - 指针明显无缘无故地改变 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46984171/

相关文章:

c - 为什么只有内核可以切换CPU执行模式?

c++ - C/C++ 中的指针和数组

c - scanf 不接收数据

java - 为什么在 Java 中不能有 "List<List<String>>"?

python - 在 Python 中取消引用列表中的列表

javascript - 无法获取按钮的onclick属性来调用JS函数

c++ - 使用宏获取函数参数 'name'

c - C 和汇编之间的链接错误

python - 根据指标对候选人列表进行排序 - Python?

C++(11) 函数的默认参数作为模板参数或函数指针