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>

// DECLARING and USING STRINGS on DATA SEGMENT

static char* _get_abc() {
    return "ABC";  // characters 'A', 'B', 'C', and the null terminator '\0' are on the
}                  // data segment, read-only section.

static void _print_string(char* s) {
    printf("%s\n", s);
}

int main(int argc, char* argv[]) {
    char* s1 = "ABC";  // on data segment because (1) we declared s1 as char* -AND-
                                               // (2) we initialized it with "…".
    printf("s1 == \"%s\"\n", s1);

    // CANNOT assign to individual characters.
    //s1[0] = 'E';  // RUN-TIME ERROR:  "Segmentation fault"
    //s1[1] = 'F';  // (same)
    //s1[2] = 'G';  // (same)
    //printf("s1 == \"%s\"\n", s1);
    
    // CAN assign one to another
    char* s2 = s1;
    printf("s2 == \"%s\"\n", s2);
    
    char* s3 = _get_abc();
    printf("s3 == \"%s\"\n", s3);

    _print_string(s3);

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

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