Usenet是一个奇怪的地方。 - Dennis M Ritchie,1999年7月29日。 C FAQ: http://www.eskimo.com/~scs/C-faq/top.html K& R答案,C书等: http://users.powernet.co.uk/eton Hi I''m trying to learn C, but I am struggling with using scanf and a struct. Iwant to define a structure and declare a variable of that type in int main.This has to be passed to a function and its values have to read and returnedfrom this function. How do you use gets() for this? I just can''t figure itout. Here is a bit of code typedef struct sStudent{char *Name;char *ID;} tStudent; void ReadStudents(tStudent student[10]) int main(){tStudent student[10];ReadStudents(student);} void ReadStudents(tStudent student[10]){????????????} 解决方案 Rather than lock the ReadStudents function down to a 10-element array, whynot pass in the size? This will entail changing the call, in main(), to: ReadStudents(student, sizeof student / sizeof student[0]); Here''s a possible ReadStudents implementation. It''s not completely robust,but it will show you the general idea: void ReadStudents(tStudent student[], size_t NumStudents){size_t ThisStudent = 0; while(ThisStudent < NumStudents){puts("Please enter the student''s name.");fgets(student[ThisStudent].Name,sizeof student[ThisStudent].Name,stdin);student[ThisStudent].Name[strlen(student[ThisStudent].Name) - 1] = ''\0'';puts("Please enter the student''s ID.");fgets(student[ThisStudent].ID,sizeof student[ThisStudent].ID,stdin);student[ThisStudent].ID[strlen(student[ThisStudent].ID) - 1] = ''\0'';++ThisStudent;}} Problems I haven''t discussed: 1) fgets might fail (it returns NULL if it does).2) User might type in more data than the buffer can hold. Unlike gets(),fgets() will not allow this to overrun your buffer, but you will getstrange results on subsequent calls (because the remaining data will beleft in the buffer). --Richard Heathfield : bi****@eton.powernet.co.uk"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.C FAQ: http://www.eskimo.com/~scs/C-faq/top.htmlK&R answers, C books, etc: http://users.powernet.co.uk/eton Undefined behaviour, guaranteed. Quite apart from using the gets() function(which is severely broken), you forgot to reserve any storage for Name. --Richard Heathfield : bi****@eton.powernet.co.uk"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.C FAQ: http://www.eskimo.com/~scs/C-faq/top.htmlK&R answers, C books, etc: http://users.powernet.co.uk/eton 这篇关于结构,指针和获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-16 20:17