these are valid :
but why is this wrong then :Code:char str[5]="good";
int a[3]={1,2,3};
char *p="hello";
int *q={1,2,3}; when char *p="hello"; is valid.
Printable View
these are valid :
but why is this wrong then :Code:char str[5]="good";
int a[3]={1,2,3};
char *p="hello";
int *q={1,2,3}; when char *p="hello"; is valid.
Character arrays and pointers were always a special case in C.
Further, some compilers (GCC) permit compond literals in the style you seek.
Compound Literals - Using the GNU Compiler Collection (GCC)
What this does is create a character array "Hello" on the stack, and points p to the beginning of it. This is also why you can't do something like p[0] = 'J'; to make it say "Jello", because "Hello" was allocated on the stack (read only), and you would get a segfault at execution.Code:char *p = "Hello";
Which is the equivalent of your integer example, does not work.Code:char *p = { 'H', 'e', 'l', 'l', 'o', '\0' };
Simply put, the behavior of "Hello" is different than the behavior of actually assigning values to elements in an array. These are just pointers, they point to values, they are "scalar" meaning they hold one value, which is the pointer to the location they point to! If you declare it an array, your compiler knows it's not a scalar, thus you can assign things like that.
If you have an array or pointer, and you call forth array[1], that just means *(array+1). It goes to array[0]'s memory address and then goes one unit (integer, character, etc) forward.
Also, you can do something like this if you want to:
Code:int p[] = { 1, 2, 3, 4 };
C doesn't actually specify where in memory to store stuff or what permissions that page/segment should have, but generally, string literals are not stored on the stack. The stack is typically readable and writable, but not executable. It's where local variables and function parameters get put, and since those variables can change, it must be writable. String literals would likely be put in a read-only section of the global data section, even if the pointer itself is a local variable (in which case the 4 bytes or whatever for p would be put on the stack, but not the string it points to).