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

char* make_asterisks_string(int num_asterisks) {
    // Allocate a buffer on the HEAP segment sufficient to store 'num_asterisks' asterisks
    // and the null terminator.

    char* asterisks = malloc(sizeof(*asterisks) * (num_asterisks + 1));
    // ∙ sizeof(*asterisks) is the number of bytes needed to store ONE object of the same
    //   type as (*asterisks).  Since asterisks is a char*, then *asterisks is a char.
    //   Therefore, sizeof(*asterisks) is the number of bytes needed to store a char on
    //   our platform.
    // ∙ sizeof(*asterisks) * (num_asterisks + 1) is the number of bytes needed to store
    //   the whole string of asterisks, plus the null terminator.
    //
    // DO NOT DO IT LIKE THIS:
    // char* asterisks = malloc(sizeof(char) * (num_asterisks + 1));
    // This is an old way and should not be used in 2023.
    for(int i = 0; i < num_asterisks; i++) {
        asterisks[i] = '*';
    }

    asterisks[num_asterisks] = '\0';  // REMEMBER!!!!  Add the null terminator.
    return asterisks;
}

int main(int argc, char* argv[]) {

    char* asterisks = make_asterisks_string(7);
    printf("asterisks == \"%s\"\n");
    // Output:
    // asterisks == "*******"
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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