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>

char* make_divider(char divider_char, int num_repetitions) {
// Return a new string consisting of «num_repetitions» divider_char's followed by a '\n'.

    // char divider[10000];  // BAD!!!  We can't predict how large num_repetitions may be.
    
    // char* new_buffer = malloc(«NUMBER_OF_THINGS» * sizeof(*new_buffer));
    //                    └─┬──┘ └─────────────────┬────────────────────┘
    //                      │     number of bytes in the buffer you want to create
    //                      │
    //                    allocates memory on the heap and returns address to that buffer.

    char* divider = malloc((num_repetitions + 2) * sizeof(*divider));
    //                     └───────┬───────────┘ └─────────────────┬────────────────────┘
    // # of chars (including '\n') plus '\0'      # of bytes required to store one char

    // POPULATE the string
    for(int i = 0; i < num_repetitions; i++) {
        divider[i] = divider_char;
    }
    divider[num_repetitions] = '\n';      // newline, as promised
    divider[num_repetitions + 1] = '\0';  // null terminator -- always needed when building
                                          // a string from scratch in memory.

    // PROBLEM #1:  You cannot return a statically allocated array¹.
    // PROBLEM #2:  We don't know how large the `divider` buffer needs to be.
    //
    //     ¹ In this or any other obvious way.  There are always tricks.
    return divider;
}


int main(int argc, char* argv[]) {
    // CREATE divider.  This allocates memory on the HEAP.
    char* divider = make_divider('-', 80);

    // PRINT message.
    printf("\n");
    printf("I woke up this morning feeling SUPER!!!\n");
    printf("%s", divider);
    printf("Where's the butler?  Hand me the butter!\n\n");
    
    // FREE memory for divider.
    free(divider);

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

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