简体   繁体   English

如何使用指针和动态内存添加新的结构学生

[英]How to add new a new structure student using pointers and dynamic memory

My current code takes user input and collects student information. 我当前的代码接受用户输入并收集学生信息。 I am trying to write a function that will allow the user to add a new student. 我正在尝试编写一个允许用户添加新学生的功能。 I reallocated the memory and passed everything into the function, but when I compile and run the program it outputs garbage for the new student instead of the new student details. 我重新分配了内存并将所有内容传递给函数,但是当我编译并运行程序时,它会为新学生输出垃圾而不是新学生的详细信息。 Any help is appreciated. 任何帮助表示赞赏。

Struct 结构

struct student
{
    char fname[20];
    char lname[20];
    float score;
};

Prototype 原型

void addStudents(struct student *s, int student_size);

Main 主要

int main()
{
    int base_number, i;
    int students;

    struct student *ptr;

    printf("Enter Number of Students: ");
    scanf("%d", &base_number);

    ptr = (struct student*)malloc(base_number * sizeof(struct student));
    students = base_number;

    printf("\nEnter Student Information\nExample: John Smith 98.50\n\n");

    for(i = 0; i < base_number; i++)
    {
        printf("Student %d: ", i+1);
        scanf("%s %s %f", (ptr+i)->fname, (ptr+i)->lname, &(ptr+i)->score);
    }

    printStudents(ptr, students);

    students++;
    ptr = realloc(ptr, students * sizeof(struct student));

    addStudents(ptr, students);


    //Getting garbage for new student
    printStudents(ptr, students);

    return 0;
}

addStudents Function addStudents函数

void addStudents(struct student *s, int student_size)
{
    printf("\nAdd A Student\nStudent Information: ");
    scanf("%s %s %f", (s+student_size)->fname, (s+student_size)->lname, &(s+student_size)->score);
}
students++;
ptr = realloc(ptr, students * sizeof(struct student));

addStudents(ptr, students);

AddStudents adds a student after the buffer. AddStudents在缓冲区后添加学生。 Either call 要么打电话

addStudents(ptr, students - 1);

Or change addStudents implementation to write to previous place in the buffer: 或者更改addStudents实现以写入缓冲区中的上一个位置:

void addStudents(struct student *s, int student_size)
{
    printf("\nAdd A Student\nStudent Information: ");
    scanf("%s %s %f", (s+student_size-1)->fname, (s+student_size-1)->lname, &(s+student_size-1)->score);
}

Do not increase students before you call addStudents . 在调用addStudents之前不要增加students

Otherwise it is out of the bounds of the array (and are editing a different student). 否则它超出了数组的范围(并且正在编辑不同的学生)。

students++;
ptr = realloc(ptr, students * sizeof(struct student));
addStudents(ptr, students);

Should be 应该

ptr = realloc(ptr, (students + 1) * sizeof(struct student));
addStudents(ptr, students);
students++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM