/* In this example, we are looking at the myriad ways that we can create a variable that holds a string and how their behavior differs. In all cases we are making use of "string literals" (text explicitly represented between ""). To compile: gcc -o 06-strings 06-strings.c -Wall To run: ./06-strings C. Andrews 2016-02-22 */ #include int main(int argc, char * argv[]){ // These thre create pointers that point to the string stored in read-only memory const char * str1 = "string1"; char * const str2 = "string2"; char * str3 = "string3"; // these two populate arrays char str4[] = "string4"; char str5[8] = "string5"; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("str3: %s\n", str3); printf("str4: %s\n", str4); printf("str5: %s\n", str5); printf("\n"); // The first difference we find comes when we try to update a character in the string // The pointers are pointing to read only memory, so the strings can't be updated // Note that the use of const in str1 is saying that str1 points to a constant char *, so the compiler knows the string can't be changed // For the other two, the compiler doesn't know, so the program crashes when we try to access that memory //str1[0] = '*'; //assignment to read only memory //str2[0] = '*'; // segfault //str3[0] = '*'; // segfault str4[0] = '*'; str5[0] = '*'; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("str3: %s\n", str3); printf("str4: %s\n", str4); printf("str5: %s\n", str5); printf("\n"); // The other thing we can try to do is point to a different string // str2 can't be changed because we declared it as const, so the compiler won't let us change its value (the address it points to) // here the const keyword is modifying the variable name itself, saying the value stored in this variable can't be changed, // as opposed to str1, which is a dynamic variable that points at a static string // str4 and str5 are arrays and we can't update the contents of an array this way str1 = "dalek1"; // str2 = "dalek2"; //read only variable str3 = "dalek3"; //str4 = "dalek4"; // can't assign to array //str5 = "dalek5"; // can't assign to array printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("str3: %s\n", str3); printf("str4: %s\n", str4); printf("str5: %s\n", str5); printf("\n"); return 0; }