memalloc_ex2.c (1087B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 /* 6 * Make N student structures, allocate memory for them and 7 * assign values to them from stdin. 8 */ 9 10 struct Student { 11 char name[32]; 12 int id; 13 float grade; 14 }; 15 16 int 17 main(int argc, char *argv[]) 18 { 19 struct Student *stud; 20 int n, i; 21 float sum; 22 23 do { 24 printf("How many students? "); 25 scanf("%d", &n); 26 getchar(); 27 } while (n <= 0); 28 29 if ((stud = malloc(n * sizeof(struct Student))) == NULL) 30 return 1; 31 32 sum = 0.0f; 33 for (i = 0; i < n; i++) { 34 printf("stud[%d].name: ", i); 35 fgets(stud[i].name, 32, stdin); 36 37 printf("stud[%d].id: ", i); 38 scanf("%d", &stud[i].id); 39 getchar(); 40 41 printf("stud[%d].grade: ", i); 42 scanf("%f", &stud[i].grade); 43 getchar(); 44 45 sum += stud[i].grade; 46 } 47 48 printf("avg: %.2f\n", sum / (float)n); 49 50 return 0; 51 }