In the following example, we create an array of structs of type Student. There is no explicit use of pointers in the examples. Struct members are accessed using the dot notation for the struct array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
/** * File: struct_students.c * Author: Risto Heinsar * Created: 10.01.2021 * Last edit: 26.01.2026 * * Description: Collects student data and finds the best student. Assumes * there can only be one best student. * * Compile using --std=c99 or later. */ #include <stdio.h> #include <stdlib.h> #define LEN_NAME 32 #define MAX_STUDENTS 8 struct Student { char name[LEN_NAME]; float avgGrade; }; int GetStudentCount(int min, int max); void ReadStudents(struct Student pupils[], int n); int GetBestStudentIndex(struct Student pupils[], int n); int main(void) { struct Student students[MAX_STUDENTS]; /* Get the number of students and store it into memory */ int numOfStudents = GetStudentCount(1, MAX_STUDENTS); ReadStudents(students, numOfStudents); /* Get the best sudent ID */ int bestStudentId = GetBestStudentIndex(students, numOfStudents); printf("The best student is: %s with a grade of %.2f\n", students[bestStudentId].name, students[bestStudentId].avgGrade); return EXIT_SUCCESS; } /** * Description: Reads the number of students, loops until input within allowed * range. * * Parameters: min - lower bound, inclusive * max - upper bound, inclusive * * Return: - */ int GetStudentCount(int min, int max) { int num; do { printf("Enter number of students (%d .. %d): ", min, max); scanf("%d", &num); } while (num < min || num > max); return num; } /** * Description: Reads students information (name, grade) * * Parameters: pupils - student array to be populated * n - number of students * * Return: - */ void ReadStudents(struct Student pupils[], int n) { for (int i = 0; i < n; i++) { printf("Enter student's name and average grade (%d / %d)\n", i + 1, n); scanf("%s %f", pupils[i].name, &pupils[i].avgGrade); } } /** * Description: Find the index of the student with the highest grade. Assumes * only one maximum. * * Parameters: pupils - student array to be populated * n - number of students * * Return: index of the student with the highest grade */ int GetBestStudentIndex(struct Student pupils[], int n) { int bestId = 0; for (int i = 1; i < n; i++) { if (pupils[bestId].avgGrade < pupils[i].avgGrade) { bestId = i; } } return bestId; } |