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
#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'.

    // BAD (and won't work)
    char divider[10000];  // DUH... nobody would make a divider >100 characters, right?

    // 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[]) {
    char* divider = make_divider('-', 80);

    printf("I woke up this morning feeling SUPER!!!\n\n");
    printf("%s", divider);
    printf("Where's the butler?  Hand me the butter!\n\n");
    
    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.