1

i'm trying to apply malloc in my code, but still having a problem, there's an error saying : "request for member 'id' in something not a structure or union".

what i want to do is to use malloc instead of array.. and store the structure in each indices, i tried array[i]->id, but bunch of garbage character stored on my text file. I also increment i and didn't use loop, coz user may only input once... this is my code:

#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
       char id[8];
       char name[30];
       char course[5];
}s1;
main(){
    int i=0;
    FILE *stream = NULL;
    stream = fopen("studentinfo.txt", "a+");    
    struct studentinfo *array[50];

    array[i] = (struct studentinfo*) malloc(sizeof(struct studentinfo));
       printf("Enter Student ID: ");
       scanf("%s", array[i].id);
       fflush(stdin);
       printf("Enter Student Name: ");
       gets(array[i].name);
       fflush(stdin);
       printf("Enter Student Course: ");
       scanf("%s", array[i].course);

       fprintf(stream, "\n%s,\t%s,\t%s", array[i].id, array[i].name, array[i].course);
       i++;
       fclose(stream);
       free(array);
    getch();
}

hope you can help me... thanks in advance :)

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
iamanapprentice
  • 411
  • 5
  • 19
  • 37
  • `fflush(stdin) ` invokes Undefined Behaviour. – Prasoon Saurav Dec 04 '10 at 04:10
  • and change the gets() function because QUOTE "it is the devil's tool of creating buffer overflow"... http://stackoverflow.com/questions/4346598/gets-function-in-c – newbie Dec 04 '10 at 04:23
  • Did you want to make an array of StudentInfo, or did you want to make an array of pointers to StudentInfo? Because you did the latter, and it seems like you wanted the former. – Karl Knechtel Dec 04 '10 at 04:08

2 Answers2

5

You're accessing the properties incorrectly.

array[i]

is a pointer to a struct, so

array[i].id

is going to give you an error. Use

array[i]->id

to dereference.

Elle H
  • 11,837
  • 7
  • 39
  • 42
3

You should initialize the array and free it like this: Am i using malloc properly?
Also... follow Zurahn's instruction.

Community
  • 1
  • 1
newbie
  • 14,582
  • 31
  • 104
  • 146