Structures
Group a student name and score into one structured record.
Complete program
#include <stdio.h>
struct Student {
char name[32];
int score;
};
int main(void) {
struct Student student = {"Mira", 92};
printf("%s scored %d\n", student.name, student.score);
struct Student *record = &student;
record->score += 3;
printf("Updated score: %d\n", student.score);
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
A structure groups fields with different types. Dot notation accesses a field through an object; arrow notation accesses a field through a pointer to that object.
The name array stores its own characters, including the null terminator. A structure may contain padding between members, so its size is not necessarily the sum of its visible field sizes. Try an array of Student records as the next exercise.
Expected output
Mira scored 92
Updated score: 95Concepts to practice
- struct
- Members
- Pointer member access
- Initialization
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.