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
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
#include <stdio.h>
#include <stdlib.h>

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

    // A string is an array of characters in memory.

    // string -- s1 is the address of the beginning of an array of char (i.e., a string)
    char* s1  = "dictionary"; // in data segment (do not change)
    printf("s1 == \"%s\"\n", s1);

    // string -- s2 is also an array of characters, this time declared in the way
    // you are probably more accustomed to from CS 159.
    char s2[] = "dictionary"; // on stack (okay to change, carefully)
    printf("s2 == \"%s\"\n", s2);

    // A string literal automatically includes the null terminator.

    // // NOT DONE YET,  THERE IS A BUG.  THIS MIGHT CRASH OR MISBEHAVE.
    // char s3[] = {100, 105, 99, 116, 105, 111, 110, 97, 114, 121};
    // printf("s3 == \"%s\"\n", s3);

    char s4[] = {100, 105, 99, 116, 105, 111, 110, 97, 114, 121, 0};
    printf("s4 == \"%s\"\n", s4);

    char s5[] = {'d', 'i', 'c', 't', 'i', 'o', 'n', 'a', 'r', 'y', '\0'};
    printf("s5 == \"%s\"\n", s5);

    char s6[] = {0104, 'i', 99, 116, 0x69, 0x6f, 'n', 'a', 'r', 'y', '\0'};
    printf("s6 == \"%s\"\n", s6);

    // s2, s4, s5, and s6 are all exactly the same to the compiler.

    return EXIT_SUCCESS;
}

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