I’ve been trying to tweak this problem from my textbook that explains arrays of structures.
My output was correct, but when I added another ‘person’ to my structure, and tried to print the result (in the 2nd print statement in displayStats()), it outputs 4 lines instead of 2. Running this code, the output is:
Hoover, Adam: 10.400000 PPG in 2005 , : 0.000000 PPG in 0 .N=ö, Ðè/: 0.000000 PPG in 1 Jane, Mary: 10.400000 PPG in 2005
This is kind of interesting because even when I comment out the second print statement (which prints the Mary Jane line), the output is still 2 lines — Hoover, Adam being line 1, and , : 0.00000 being line 2. When I make all 4 fields in the array [32], I still get 4 lines of output, but the middle 2 lines are changed a bit.
I’m probably missing something really simple, but the goal is just to have 2 lines of output with Hoover, Adam and Jane, Mary.
#include <stdio.h>
#include <string.h>
struct person { /* "person" is name for structure type */
char first[32]; /* first field of structure is array of char */
char last[32]; /* second field is array of char */
int year; /* third field is int */
double ppg; /* fourth field is double */
char second[31];
char third[31];
int year1;
double ppo;
}; /* ending ; means end of structure type definition */
displayStats(struct person Input) {
printf("%s, %s: %lf PPG in %d\n", Input.last, Input.first, Input.ppg, Input.year);
printf("%s, %s: %lf PPG in %d\n", Input.third, Input.second, Input.ppo, Input.year1);
}
int main(int argc,char *argv[]) {
struct person teacher;
struct person another;
teacher.year=2005;
teacher.ppg=10.4;
strcpy(teacher.first,"Adam");
strcpy(teacher.last,"Hoover");
displayStats(teacher);
another.year1=2005;
another.ppo=10.4;
strcpy(another.second,"Mary");
strcpy(another.third,"Jane");
displayStats(another);
return (0);
}
You are seeing garbage because for teacher,
secondandthirdaren’t assigned, and for another,firstandlastaren’t assigned?Why do you have
secondandthirdfields? Remove them, usefirstandlastfor both, and remove the second line indisplayStats, and it should work.