1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct {
    int x;
    int y;
} Point;

int main(int argc, char* argv[]) {
    // this is not an assignment, this is an initializer
    // C compiler can infer the meaning of {} from the variable type
    Point p1 = {.x = 5, .y = 7};
    printf("(p1.x, p1.y) == (%d, %d)\n", p1.x, p1.y);

    Point* a_p1 = &p1;
    
    printf("(a_p1->x, (*a_p1).y) == (%d, %d)\n", a_p1->x, (*a_p1).y);
    a_p1->x = 8;

    // can malloc structs
    Point* a_p2 = malloc(sizeof(*a_p2));
    // a_p2 is unitialized!!!
    // initializing on the next two lines
    a_p2->x = 7;
    a_p2->y = 9;
    printf("(a_p2->x, a_p2->y) == (%d, %d)\n", a_p2->x, a_p2->y);

    // overwrting the data in p1 from *a_p2
    p1 = *a_p2;
    printf("(p1.x, p1.y) == (%d, %d)\n", p1.x, p1.y);

    // cleaner way to initialize struct
    Point* a_p3 = malloc(sizeof(*a_p3));
    *a_p3 = (Point) { .x = 7, .y = 9 };
    // wrong: cannot use {} without (Point) for assignment of Point
    //*a_p3 = { .x = 7, .y = 9 };
    // wrong: cannot assign Point to Point*
    //a_p3 = (Point) { .x = 7, .y = 9 };
    // wrong: cannot make a Point* initilizer
    //a_p3 = (Point*) { .x = 7, .y = 9 };
    // wrong: cannot make a Point* initializer
    //*a_p3 = (Point*) { .x = 7, .y = 9 };
    printf("(a_p3->x, a_p3->y) == (%d, %d)\n", a_p3->x, a_p3->y);

    // not recommended, but works: sets y=0
    // better to specifically set to 0
    p1 = (Point) { .x = 5 };
    // wrong: cannot use {} without (Point) for assignment of Point
    //p1 = { .x = 5, .y = 0 };
    printf("(p1.x, p1.y) == (%d, %d)\n", p1.x, p1.y);

    // free malloced addresses
    free(a_p2);
    free(a_p3);
    // wrong: cannot free a_p1, it is a stack variable
    //free(a_p1);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.