Использование структурных функций и указателей в C - PullRequest
0 голосов
/ 28 ноября 2018

То, что я пытаюсь сделать, это использовать функцию struct, которая принимает значения, содержащиеся в структуре Student, создает структуру Student, а затем возвращает указатель студента.Итак, в основном:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student_struct
{
    char name[16];
    int age;
    float gpa;

}Student;


Student *makeStudent(char name[16], int age, float gpa)
{
    Student *s = (Student *) malloc(sizeof(Student));
    //FIXME: Make your code changes here....
    strcpy(s->name, name);
    s->age=age;
    s->gpa=gpa;
    return s;

}

//Display the values of all students in the class
void displayClass(Student classArray[], int size)
{
    int i;
    for(i=0;i<size;i++){
        printf("  %s, %d, %.1f\n", classArray[i].name, classArray[i].age, classArray[i].gpa);
    }
}

int main()
{
    //FIXME: Implement make student function
    Student *adam = makeStudent("adam", 18, 2.0);
    Student *beth = makeStudent("beth", 19, 3.2);
    Student *chris = makeStudent("chris", 18, 3.6);
    Student *daphney = makeStudent("daphney", 20, 3.9);
    Student *erin = makeStudent("erin", 19, 2.6);

    const int CLASS_SIZE = 5;
    Student classArray[CLASS_SIZE];
    classArray[0] = *adam;
    classArray[1] = *beth;
    classArray[2] = *chris;
    classArray[3] = *daphney;
    classArray[4] = *erin;

    displayClass(classArray, CLASS_SIZE);

    //deallocate memory
    free(adam);
    free(beth);
    free(chris);
    free(daphney);
    free(erin);

    return 0;
}

И вывод, который я хотел бы получить:

adam, 18, 2.0
beth, 19, 3.2
chris, 18, 3.6
.... (continues from there)

Но вместо этого я получаю:

 , 0, 0.0
 , 0, 0.0
 , 0, 0.0
 , 0, 0.0
 , 0, 0.0

Я думаю,это связано с функцией

Student *makeStudent(char name[16], int age, float gpa)

, но я не уверен.Есть намеки?Не ищу ответа!

...