指针变化显然没有理由 - C.

时间:2017-10-27 22:22:21

标签: 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'在函数完成后,struct会被遗忘在内存中吗?如果是这样,如何解决?

1 个答案:

答案 0 :(得分:4)

student_root = malloc(sizeof(struct student));

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

初始化student_root以指向堆位置后,再将几行设置为指向自动局部变量,当您从此函数返回时,其内存将被其他代码重写。< / p>

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