c - 从函数返回数组地址无效

标签 c arrays function pointers struct

我有一个 C 程序,用户可以在其中输入多组成绩。一切正常。 GPA 计算正确等。但是,当打印回数字时,由于某种原因,Student 结构中的两个指针都指向相同的地址,导致两个学生在打印信息时显示第二个学生的成绩。其余信息都是正确的,只是等级相同。

我唯一能想到的是成绩数组的第二次初始化覆盖了第一次。我不明白为什么会发生这种情况或如何解决它。

程序IO示例如下:

Enter the number of students:> 2
Enter the number of grades to track:> 3

There are 2 students.
There are 3 grades.

Enter information for student:
        Enter SID:> 101
        Enter last name:> Enright
        Enter first name:> Reed
        Enter grades (separated by space):> 70.1 60 92

Enter information for student:
        Enter SID:> 123
        Enter last name:> Claire
        Enter first name:> Heidi
        Enter grades (separated by space):> 82.5 96.1 89.0

Student ID #101:
        Name:   Reed Enright
        Grades: 82.5 96.1 89.0
        GPA:    74.03
Student ID #123:
        Name:   Heidi Claire
        Grades: 82.5 96.1 89.0
        GPA:    89.20

这是完整的代码:

#include <stdio.h>
#define NAME_SIZE 25

typedef struct {
        int sid;
        char last_name[NAME_SIZE];
        char first_name[NAME_SIZE];
        float *grades;
        float gpa;
} Student;

// function prototypes

// get student information
Student prompt_student(int number_of_grades); 
// calculate the gpa based on the grades
float calculate_gpa(Student student, int number_of_grades); 
// prints all of the students
void print_all_students(Student students[], int number_of_students, int number_of_grades);

int main(){
        // initialise variables
        int number_of_students;
        int number_of_grades;

        // prompt for number of students
        printf("\nEnter the number of students:> ");
        scanf("%d", &number_of_students);
        // prompt for number of grades
        printf("Enter the number of grades to track:> ");
        scanf("%d", &number_of_grades);

        // confirm the above
        printf("\nThere are %d students. \nThere are %d grades.\n",
                        number_of_students, number_of_grades);

        // initialise student list
        Student students[number_of_students];
        // get and store student information
        for(int i = 0; i < number_of_students; i++){
                students[i] = prompt_student(number_of_grades);
        }

        // confirm the above
        print_all_students(students, number_of_students, number_of_grades);

        return 0;
}

Student prompt_student(int number_of_grades){
        // initialise student variable
        Student student;
        float grades[number_of_grades];
        printf("\nEnter information for student: \n");

        // prompt for student info
        printf("\tEnter SID:> ");
        scanf("%d", &(student.sid));

        printf("\tEnter last name:> ");
        scanf("%s", student.last_name);

        printf("\tEnter first name:> ");
        scanf("%s", student.first_name);

        printf("\tEnter grades (separated by space):> ");
        for(int i = 0; i < number_of_grades; i++){
                scanf("%f", &grades[i]);
        }
        student.grades = grades;

        student.gpa = calculate_gpa(student, number_of_grades);

        return student;
}

float calculate_gpa(Student student, int number_of_grades){
        float total = 0; // initialise variable for sum of grades
        // add all grades together
        for(int i = 0; i < number_of_grades; i++){
                total += student.grades[i];
        }
        // return average
        return total / number_of_grades;
}

void print_all_students(Student students[], int number_of_students, int number_of_grades){
        // loop through all students
        for(int i = 0; i < number_of_students; i++){
                // print student info
                printf("\nStudent ID #%d:", students[i].sid);
                printf("\n\tName:\t%s %s", students[i].first_name, students[i].last_name);
                printf("\n\tGrades:\t");
                for(int n = 0; n < number_of_grades; n++){
                        printf("%.1f ", students[i].grades[n]);
                }
                printf("\n\tGPA:\t%.2f", students[i].gpa);
        }
        printf("\n");
}

最佳答案

问题是在函数 prompt_student 中声明了局部数组

float grades[number_of_grades];

并将此局部数组的第一个元素的地址分配给结构Student的数据成员grades

student.grades = grades;

所以这个数据成员对于函数的每次调用总是具有相同的地址。此外,该程序具有未定义的行为,因为在退出该函数后,本地数组不再存在。一般情况下会被销毁。

您必须动态分配一个数组并将分配的数组的地址分配给数据成员grades

例如

float *grades = malloc( number_of_grades * sizeof( float ) );

很明显,在 main 中,当结构的相应对象不再使用时,您应该释放分配的内存。

关于c - 从函数返回数组地址无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816126/

相关文章:

javascript - JavaScript 函数可以返回自身吗?

function - Golang 包结构返回缓冲区

c++ - 在 32 位字位模式中找到 "edges"

c - 在开始使用方法进行 C 编程时

c - C 中的浮点加法

python - 在 numpy 数组中找到一段 Trues

c - 在c中读取和打印矩阵

javascript - React-Native for-loop through large size array 性能问题

javascript - 从 children 数组中获取特定的 child

Javascript 函数需要允许数字、点和逗号