bgc icon indicating copy to clipboard operation
bgc copied to clipboard

String literals

Open anordin95 opened this issue 2 years ago • 0 comments

I've been mostly progressing through the textbook serially (i.e. chapter 1 then 2, then 3, etc.), and got pretty confused at the end of section 7.4.

It was so bewildering to me that strings, which are so similar to arrays and pointers, can't be modified depending on the style of the initialization. I dug for a while and discovered this is largely due to the ability to express strings as literals, something which can't be done for arrays! And, how the compiler handles those literals. https://c-faq.com/decl/strlitinit.html

I tried to add a section to explain why that's the case without leveraging any ideas a newer reader who's been reading serially may not have covered yet, such as memory segments (i.e. stack, heap, instruction).

int arr1[] = {1,2,3};
char str1[] = {'a', 'b', 'c'};
    
// Note: arr2 & str2 are pointers to 0x1 and the ASCII-decode of the character ‘a’ — 0x61 or 97. 
int *arr2 = {1,2,3};
char *str2 = {'a', 'b', 'c'};

// No equivalent way to do this for arrays!
char *str3 = "abc";

anordin95 avatar Jan 23 '24 06:01 anordin95