3 ms·
One other difference on modern compilers relating specifically to character arrays: This will work fine: char arr[] = "stuff"; printf("arr:%s\n", arr
by wsxcde 12y ago
One other difference on modern compilers relating specifically to character arrays:
This will work fine:
char arr[] = "stuff";
printf("arr:%s\n", arr);
arr[0] = 'b'; arr[1] = 'l';
printf("arr:%s\n", arr);
arr is allocated on the stack (not heap, sorry about the mistake) and is mutable.
But the following will segfault:
char* ptr = "stuff";
printf("ptr:%s\n", ptr);
ptr[0] = 'b'; ptr[1] = '1';
printf("ptr:%s\n", ptr);
Strings are allocated in the read-only data segment. Technically you can only write const char* ptr = "stuff", but due to wanting to remain backward compatibile, gcc will let you write the above and not even warn you unless you use -Wall or similar.
- deanstag 12y agoYeah. I was exploring exactly this problem when i came across this original article. Later i saw that "char arr[] = "stuff" " actually inserts assembly code that puts the value stuff into the stack. That was interesting news to me. stackoverflow.com/questions/29184100/char-array-and-pointer-initialization-semantics/29184190#29184190