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

/*
 * This structure is somewhat similar to the maze used in the homework.
 *
 * This version shows how to allocate and deallocate the structure with just
 * one call each to malloc(…) and free(…).
 */

typedef struct _Party {
    int    num_people;   // 4 bytes on our platform
    int    start_time;   // 4 bytes on our platform
    char*  name;         // 8 bytes on our platform
    char** daze;         // 8 bytes on our platform
} Party;

int main(int argc, char* argv[]) {
    int num_rows = 4;
    int num_cols = 4;
    Party* party = malloc(sizeof(*party) +                      // struct object itself
                          sizeof(*party -> daze) * num_rows +   // row addresses
                          sizeof(**party -> daze) * num_cols * num_rows); // rows (chars)

    party -> name = "Birthday";          // on data segment
    party -> num_people    = 50;         // # of people
    party -> start_time    = 11;         // start time
    party -> daze = (void*)(party + 1);  // byte right after struct
    char* beginning_of_rows = (void*)(party -> daze + num_rows);

    for(int i = 0; i < num_rows; i++) {
        party -> daze[i] = beginning_of_rows + num_cols * i; // set address of this row
        memcpy(party -> daze[i], "****", num_cols);          // set content of this row
    }

    free(party);   // Now tear it all down.

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

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