C structures and records
Group related fields into a typed record.
On this page
Variables, arrays, and dot member access.
- Group related fields into a typed record.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
#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;
}Ada 82 Ada 95
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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;}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 |
Behind the scenes
How C processes this code
The C compiler produces a native program. Variables occupy memory, and execution enters main.
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.