I have not been able to find an answer to this question (I have looked so apologies if it is a repeat). In C when initializing a char array there are roughly two methods as I know it:
char[] a = "Hello";
char * b = "Hello";
These achieve the same result but the second initialization for 'b' confuses me. I understand the initialization for 'a' as it is the somewhat the equivalent to *(char *a) = "Hello"
assuming that memory has been allocated etc etc ...
But the syntax for the initialization of 'b' looks to me like 'b' is a pointer, pointing to an address "Hello" which of course makes no sense unless the ASCII values are being used.
As far as I have seen there are no equivalents to 'b's initialization for intergers or another data type.
If anyone could offer an explanation that would be great ! I have been using C for a long time and this one has always slightly bugged me and I have not been able to think of/find an answer
CodePudding user response:
These achieve the same result
Not quite.
char[] a = "Hello";
understand the initialization for 'a' as it is the somewhat the equivalent to *(char *a) = "Hello"
*(char *a) = "Hello"
is non-sensical to me, so I wouldn't agree it to be equivalent. a
is an array. Its size is deduced from the initialiser (6 elements).
char * b = "Hello";
But the syntax for the initialization of 'b' looks to me like 'b' is a pointer,
Correct. b
is a pointer, Hence why it is different from a
which is an array.
This one is ill-formed in C . This is because string literals are arrays of const char
in C and those don't implicitly convert into pointers to non-const char (since C 11).
pointing to an address "Hello" which of course makes no sense
Incorrect. b
points to the address of the first element of "Hello".
CodePudding user response:
"Hello" is a string literal. In an asm dump, you will see that the memory for it will be reserved in the .data section. So I think that b is just a pointer to preallocated and initialized memory.