# Problem printing data from an array of structures

• 04-27-2011
goat37
Problem printing data from an array of structures
Code:

``` #include <stdio.h> #include <stddef.h>     typedef struct     {         char name[50];         float weight;         float height;         int eaten;     }Grue;  Grue MakeAGrue();  void PrintAGrue(FILE *); int main (void) {     FILE *fp;     int i = 0;     Grue grueAr[5];     Grue *grueptr;     Grue returngrue;     if((fp = fopen("GrueData.dat", "wb+")) == NULL)     {         printf("Error opening file.\n");         exit(0);     }     for(i=0;i<2;i++) //gets 5 grue structures and places them in the grueAr.     {         returngrue = MakeAGrue();         grueAr[i] = returngrue;         grueptr = &returngrue;         fwrite(grueptr, sizeof(Grue), 2, fp);     }     fclose(fp);  //close the file     if((fp = fopen("GrueData.dat", "rb")) == NULL) //reopen the file in read binary.     {         printf("Error opening file.\n");         exit(0);     }     PrintAGrue(fp);     return 0; } Grue MakeAGrue() {     Grue grue1;     printf("Enter the Grue's name: ");     gets(grue1.name);     printf("Enter %s's height: ", grue1.name, grue1.height);     scanf("%f", &grue1.height);     fflush(stdin);     printf("Enter %s's weight: ", grue1.name, grue1.weight);     scanf("%f", &grue1.weight);     fflush(stdin);     printf("How many items has %s eaten? ", grue1.name, grue1.eaten);     scanf("%d", &grue1.eaten);     fflush(stdin);     printf("\n");     return grue1; } void PrintAGrue(FILE *fp) {     Grue grueAr[5];     int i = 0, j = 0;     int numread = 0;     fread(grueAr, sizeof(Grue), 2, fp);     for(i=0;i<2;i++)     {         printf("i is %d\n", i);         printf("PRINT FUNCTION LOOP    This grue is called %s and is %2.2f feet tall, \n", grueAr[i].name, grueAr[i].height);         printf(" PRINT FUNCTION LOOP    weights %6.2f pounds, and has eaten %d things.\n\n", grueAr[i].weight, grueAr[i].eaten);             } }```
• 04-27-2011
goat37
Sorry, forgot to add comments. I can't figure out why this code keeps printing out the first structure in the array even though the for loop in the "PrintAGrue" function cycles ok.
• 04-27-2011
cas
When you're writing a grue, you're telling fwrite() there are two members, but there are not. You're writing each time you read a grue, so presumably you only want to write the just-created grue. Tell it there is only one member to write.

Alternatively, you could pull the fwrite() out of the loop, and do something like:
Code:

`fwrite(grueAr, sizeof(Grue), 2, fp);`
This way you write the whole array (well, the part you filled) in one fell swoop.

On another note, fflush(stdin) is undefined behavior. It may do what you want on your platform, but there's no guarantee that it'll do what you expect on other systems (it doesn't on mine, for example).
• 04-27-2011
goat37
Thanks, I made the adjustment and it's working great.