2010-12-04 56 views
1

我想在我的代碼中應用malloc,但仍然有問題,有一個錯誤說:「請求成員'id在某些不是結構或聯盟」。在malloc問題

我想要做的就是使用malloc而不是數組.. ..並將結構存儲在每個索引中,我試過數組[i] - > id,但存儲在我的文本文件上的一堆垃圾字符。我還增加我並沒有使用循環,怎麼把用戶只能輸入一次......這是我的代碼:

#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(); 
} 

希望你能幫助我...在此先感謝:)

+0

`fflush(stdin)`調用未定義的行爲。 – 2010-12-04 04:10:14

+0

並更改gets()函數,因爲QUOTE「它是創建緩衝區溢出的惡魔工具」... http://stackoverflow.com/questions/4346598/gets-function-in-c – newbie 2010-12-04 04:23:23

+0

你想做一個StudentInfo數組,還是您想要創建一個指向StudentInfo的指針數組?因爲你做了後者,而且看起來你想要前者。 – 2010-12-04 04:08:09

回答

5

您正在訪問的屬性不正確。

array[i]

是一個指向一個結構,所以

array[i].id

是要給你一個錯誤。使用

array[i]->id

取消引用。