微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我想在 C 中创建一个链表并对其执行某些功能但是在我的代码中找不到错误

如何解决我想在 C 中创建一个链表并对其执行某些功能但是在我的代码中找不到错误

函数 display 不打印学生的 id,而是一些数字。指针的值被正确分配,当我打印它们时,它们应该是。但我无法打印学生的 id。你能帮我解决这个问题吗?

我得到这个作为输出

Enter Student ID
23
New Student Created
The id of student at position 1 is 12672416
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void displayList();
void insertAtFirst();
struct Student * createStudentNode();

struct Student {
    int id;
    struct Student * nextStudent;
};
struct Student * startStudent;

int main(int argc,char * argv[]) {
    insertAtFirst();
    displayList();
    return 0;
}

void displayList() {
    int x = 1;
    struct Student * tempStudent = (struct Student * ) malloc(sizeof(struct Student * ));
    if (startStudent == NULL) {
        printf("The list is empty.\n");
    } else {
        tempStudent = startStudent;

        while (tempStudent != NULL) {
            printf("The id of student at position %d is %d\n",x,tempStudent -> id);
            tempStudent = tempStudent -> nextStudent;
            x++;
        }
    }
}

void insertAtFirst() {
    struct Student * t;
    struct Student * tempStudent;

    tempStudent = createStudentNode();
    printf("Enter Student ID\n");
    scanf("%d",tempStudent -> id);
    printf("New Student Created\n");
    tempStudent -> nextStudent = NULL;

    if (startStudent == NULL) {
        startStudent = tempStudent;
    } else {
        tempStudent -> nextStudent = startStudent;
        startStudent = tempStudent;
    }
}

//This method creates a new Student structure and returns it address
struct Student * createStudentNode() {
    struct Student * n;
    n = (struct Student * ) malloc(sizeof(struct Student));
    n -> nextStudent = NULL;
    return n;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。