C structures and records
Group related fields into a typed record.
C
#include <stdio.h>
#include <assert.h>
struct Student { char name[20]; int score; };
int main(void) {
struct Student first = {"Ada", 82};
struct Student second = first;
second.score = 95;
printf("%s %d\n", first.name, first.score);
printf("%s %d\n", second.name, second.score);
assert(first.score == 82);
return 0;
}Output
Ada 82 Ada 95
Explanation
A struct combines fields under a named type. It can represent one student with a name and a score while keeping their association explicit.
Assigning one struct variable to another copies its member values. The fixed char array is part of the struct, so it is copied too; pointer members would copy addresses instead of deep-copying pointed-to data.
Explore the dry run
Guided walkthroughReady
1
#include <stdio.h>2
#include <assert.h>3
struct Student { char name[20]; int score; };4
int main(void) {5
struct Student first = {"Ada", 82};6
struct Student second = first;7
second.score = 95;8
printf("%s %d\n", first.name, first.score);9
printf("%s %d\n", second.name, second.score);10
assert(first.score == 82);11
return 0;12
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Initialize one record. | first = {Ada, 82} | — | |
| Copy the complete struct value. | second = {Ada, 82} | — | |
| Change only the second record. | first.score = 82, second.score = 95 | — | |
| Print the original. | first.score = 82, second.score = 95 | Ada 82 | |
| Print the copy. | first.score = 82, second.score = 95 | Ada 82 Ada 95 |
Cost and common mistakes
O(s) copying for a record of size s; this fixed record has bounded size.
- The name array needs room for its terminator.
- C structs have data members but no built-in class methods or inheritance.
Try it yourself
Set second.name[0] to 'E'. Does first.name change?
Reveal answer and reasoning
No. The arrays are separate; first prints Ada and second prints Eda.