← العودة إلى الدورة: C programming from scratch

Structures (struct), typedef and pointers to structures

الفيديو قريبًا

Arrays group data of the same type, but a contact, a product or a student mix types: a name (text), an age (integer), a grade (real). To group data of different types under a single name C offers the struct. It is the basis for modeling real-world entities and, together with dynamic memory, for building data structures such as lists and trees.

Defining and using a struct

A struct is defined with the word struct, a name and the fields in braces, ending with a semicolon. It defines a new type, not a variable. Then you declare variables of that type and access the fields with the dot operator. You can initialize it with braces, preferably with designated initializers (.field = value), which are clearer and zero whatever you omit. A struct is copied whole by assignment, including an array inside it.

c
#include <stdio.h>
#include <string.h>

struct Student {
    char name[32];
    int age;
    double grade;
};

int main(void) {
    struct Student a = { .name = "Ana", .age = 20, .grade = 8.5 };
    struct Student b = a;                 /* copies every field */

    snprintf(b.name, sizeof(b.name), "%s", "Bruno");
    b.grade = 7.0;

    printf("%s, %d years, grade %.1f\n", a.name, a.age, a.grade);
    printf("%s, %d years, grade %.1f\n", b.name, b.age, b.grade);
    printf("sizeof(struct Student) = %zu\n", sizeof(struct Student));
    return 0;
}

Notice that name is filled with snprintf and not with an assignment: an array field cannot be assigned, it must be copied. It is also good to know that the size of a struct can be larger than the sum of its fields, because the compiler adds padding to align data in memory.

typedef

Writing struct Student every time is awkward. typedef creates a type alias: typedef struct { ... } Student; lets you declare variables with plain Student. It is also used to give meaningful names to basic types, like typedef unsigned int Id. A typedef does not create a new type, only an alternative name. When a struct must refer to itself (linked lists) it needs a tag name, as you will see in the next lesson.

Pointers to struct and the arrow operator

Passing a large struct by value copies all its fields; it is more efficient to pass a pointer. To access a field through a pointer you write (*p).field, or more conveniently p->field, the arrow operator. If the function must not modify the struct, it takes const Student *. This is the usual way of working with structures in C, and also the way for a function to fill or modify a caller's structure.

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[32];
    int age;
    double grade;
} Student;

static void print_student(const Student *s) {
    printf("%-10s %3d %5.1f\n", s->name, s->age, s->grade);
}

static void curve(Student *s, double bonus) {
    s->grade += bonus;
    if (s->grade > 10.0) {
        s->grade = 10.0;
    }
}

int main(void) {
    Student class_list[3] = {
        { .name = "Ana",   .age = 20, .grade = 8.5 },
        { .name = "Bruno", .age = 22, .grade = 6.0 },
        { .name = "Carla", .age = 21, .grade = 9.8 },
    };

    for (size_t i = 0; i < 3; i++) {
        curve(&class_list[i], 0.5);
        print_student(&class_list[i]);
    }

    Student *dynamic = malloc(sizeof *dynamic);
    if (dynamic == NULL) {
        return 1;
    }
    *dynamic = class_list[0];            /* copy a whole struct */
    print_student(dynamic);
    free(dynamic);
    return 0;
}

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →