-2

how can I use a structure as a parameter to a function? I tried this:

struct
{
    char name[30];
    char section[20];
    float grade;
}student[30];

After reading and storing the information to the structure, I called the function that writes the data into a file:

show(f,n,student); //n is the number of students

And this is the show function:

void show(FILE *f,int n, struct elev);
{
...
}

Thank you.

1 Answers1

2

You'll better name your structure:

struct student_st {
  char name[30];
  char section[20];
  float grade;
};

Since you have several students, you probably want to pass a pointer to (an array of) them:

void show(FILE *f,int n, struct student_st* s) {
  assert (f != NULL);
  assert (s != NULL);
  for (int i=0; i<n; i++) {
    fprintf(f, "name: %s; section: %s; grade: %f\n",
            s->name, s->section, s->grade);
  };
  fflush(f);
}

You'll use it like:

#define NBSTUDENTS 30
struct student_st studarr[NBSTUDENTS];
memset (studarr, 0, sizeof(studarr));
read_students (studarr, NBSTUDENTS);
show (stdout, NBSTUDENTS, studarr);

Learn that arrays are decaying into pointers.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547