C · Course navigation

C structures and records

Group related fields into a typed record.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2#include <assert.h>
3struct Student { char name[20]; int score; };
4int 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading