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

char* repeat_char(char char_to_repeat, size_t num_times) {
    // Ex: repeat_char('*', 3) ⇒ "***"

    // Allocate buffer sufficient for 'num_times' characters plus '\0'
    char* s = malloc(sizeof(*s) * (num_times + 1));

    // Fill buffer with 'char_to_repeat'
    for(size_t i = 0; i < num_times; i++) {
        s[i] = char_to_repeat;
    }

    // Add null terminator
    s[num_times] = '\0';

    return s;
}

void print_string(char* s) {
    // Equivalent to:  printf("%s", s);
    for(int i = 0; s[i] != '\0'; i++) {
        fputc(s[i], stdout);
    }
}

int main(int argc, char* argv[]) {
    char* s = repeat_char('@', 3); // ⇒ "@@@"
    print_string(s); // same as printf("%s", s)
    free(s);
    return EXIT_SUCCESS;
}

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