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

int main(int argc, char* argv[]) {
    
    int* a_n = malloc(sizeof(*a_n));
    // PITFALLS
    // int* a_n = malloc(4);   // BAD --- Requires remembering size of an int.
    //                                    Won't work on another platform where an int
    //                                    is not 4 bytes.
    // int* a_n = malloc(sizeof(int));  // BAD --- repeats the specification of the type
    // int* a_n = (int*) malloc(sizeof(*a_n));  // BAD --- repeats specification of type
    //                                          //         TYPECASTS are EVIL!!!!!
    // int* a_n = (int*) malloc(sizeof(int));  // BAD --- both problems
    // int* a_n = malloc(sizeof(a_n));  // BAD --- don't forget the asterisk
    //                                  //         type of *a_n is int  → sizeof(*a_n) == 4
    //                                  //         type of  a_n is int* → sizeof(a_n)  == 8
    // 

    *a_n = 5;  // Remember:  *α = β means "store value β at address α."
    // PITFALLS
    // a_n = 5;  // COMPILER ERROR -- trying to assign an int (5) to an int* (a_n).

    printf("*a_n == %d\n", *a_n);  // Remember:  *a_n means "value at (address) a_n"
    // PITFALLS
    // printf("*a_n == %d\n", a_n);
    //           // COMPILER ERROR -- %d takes an int but a_n is an int*.

    free(a_n);
    // PITFALLS
    // free(*a_n)  // COMPILER ERROR --- free(…) takes an address but *a_n is an int.

    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.