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

#define log_str(n) printf("%s == \"%s\"\n", #n, (n))
#define log_addr(n) printf("%s == %p\n", #n, (void*)(n))

int main(int argc, char* argv[]) {
    char stack_str[] = "ABC";
    log_str(stack_str);
    log_addr(stack_str);

    char* data_str = "Hello World";
    log_str(data_str);
    log_addr(data_str);

    // step 1: figure out the size of the string
    int str_len = strlen(data_str);
    // str_len is the logical length of my string
    // step 2: allocate the string
    char* heap_str = malloc(sizeof(*heap_str) * (str_len + 1));
    // step 3: fill in the string
    strcpy(heap_str, data_str);

    log_str(heap_str);
    log_addr(heap_str);
    free(heap_str);

    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.