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

#define log_int(n) printf("%s == %d\n", #n, (n))
#define log_addr(n) printf("%s == %p\n", #n, (void*)(n))
#define log_long(n) printf("%s == %ld\n", #n, (n))

void fill_array(int* num_list, int size) {
    for (int i = 0; i < size; i++) {
        num_list[i] = i+1;
    }
}

int main(int argc, char* argv[]) {
    int stack_numbers[5]; 
    int stack_numbers_len = sizeof(stack_numbers) / sizeof(*stack_numbers);
    /*
     * this is invalid C, a stack array cannot be a variable size
    int stack_numbers_len = 5;
    int stack_numbers[stack_numbers_len];
     */
    stack_numbers[0] = 0;
    // neat trick: you can offset the start of an array you pass into
    // an array function, as long as the size is still within the offseted array
    fill_array(stack_numbers + 1, stack_numbers_len - 1);


    int heap_numbers_len = 5;
    int* heap_numbers = malloc(sizeof(*heap_numbers) * heap_numbers_len);
    // this trick for getting the size only works for stack allocated arrays
    // intrestingly the compiler is smart enough to catch this
    // log_long(sizeof(heap_numbers) / sizeof(*heap_numbers));
    fill_array(heap_numbers, heap_numbers_len);

    log_int(heap_numbers[0]);
    log_int(heap_numbers[1]);
    log_int(heap_numbers[2]);
    log_int(heap_numbers[3]);
    log_int(heap_numbers[4]);
    log_int(stack_numbers[0]);
    log_int(stack_numbers[1]);
    log_int(stack_numbers[2]);
    log_int(stack_numbers[3]);
    log_int(stack_numbers[4]);

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

© Copyright 2024 Alexander J. Quinn & David Burnett         This content is protected and may not be shared, uploaded, or distributed.