char a[] = "hello";
and
char *a = "hello";
Get stored in different places.
char a[] = "hello"
In this case, a becomes an array(stored in the stack) of 6 characters initialized to "hello\0". It is the same as:
char a[6];
a[0] = 'h';
a[1] = 'e';
a[2] = 'l';
a[3] = 'l';
a[4] = 'o';
a[5] = '\0';
char *a = "hello"
Inspect the assembly(this is not all the assembly, only the important part):
.file "so.c"
.text
.section .rodata
.LC0:
.string "hello" ////Look at this part
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movq $.LC0, -8(%rbp)
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
See
.section .rodata
.LC0:
.string "hello"
This is where the string is stored. char a[] is stored in the stack while char *a is stored wherever the compiler likes. Generally in rodata.
char tmp[] = "hello"is an array of 6 characters initialized to"hello\0"(it has automatic storage duration and resides within the program stack).char *tmp = "hello";is a pointer initialized with the address for the String Literal"hello\0"that resides in readonly memory (generally within the.rodatasection of the executable). (readonly on all but a few non-standard implementations) An array is converted to a pointer to its first element on access.charpointers, always dochar const* ptr = "some literal";– otherwise you almost certainly will run into modifying the literal at some point in the future, which is UB, as stated above. Being able to assign immutable literals tochar*pointers is a legacy from the very first days of C whereconstdid not yet exist.