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
#include <stdio.h>
#include <stdlib.h>

struct Point {
    int x, y;
    struct Point* next_point;
};

int main(int argc, char *argv[]) {
    // You use the heap when you don't know many things you need to allocate space for at
    // compile-time and/or when you need things to not be destroyed when a function returns.
    
    int num_points = 3;
    struct Point* points = malloc(sizeof(*points) * num_points);
    // struct Point points[num_points];  // WHY NOT??? ... no variables in array declaration
    points[0].x = 1;
    points[0].y = 2;
    points[0].next_point = &(points[1]);
    points[1].x = 4;
    points[1].y = 10;
    points[1].next_point = &(points[2]);
    points[2].x = 7;
    points[2].y = 2;
    points[2].next_point = &(points[0]);
    // Same as this (below), but &(points[0]) better expresses what you actually *mean*.
    // points[2].next_point = points;

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

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