Reputation: 1256
In this example seems that both strings "jesus" are equals(same memory location).
printf("%p\n","jesus");
printf("%p\n","jesus");
Also note that:
printf("%p\n",&"jesus");
printf("%p\n","jesus");
prints the same, but:
char* ptrToString = "jesus";
char* ptrToString = &"jesus"; //ERROR
So i wanna know how an unassigned string is stored in memory and how to point it...
Upvotes: 1
Views: 249
Reputation: 146191
C is a carefully specified language and we can make many observations about your examples that may answer some questions.
array of char
.nul
bytes can be embedded with \0
.In order to make that last line work, you need:
char (*ptrToString)[] = &"jesus"; // now not an ERROR
Upvotes: 1
Reputation: 477454
First off, why are "jesus"
and &"jesus"
the same: "jesus"
is an array of type const char[6]
, and it decays to a pointer to the first element. Taking the address of the array gives you a pointer to an array, whose type is const char (*)[6]
. However, the pointer to the array is numerically the same as the pointer to its first element (only the types differ).
This also explains why you have an error in the last line - type type is wrong. You need:
const char (*pj)[6] = &"jesus";
Finally, the question is whether repeated string literals have the same address or not. This is entirely up to the compiler. If it were very naive, it could store a separate copy for each occurrence of a string literal in the source code. If it is slightly cleverer, it'll only store one unique copy for each string literal. String literals are of course stored in memory somewhere, typically in a read-only data segment of the program image. Think of them as statically initialized global variables.
One more thing: Your original code is actually undefined behaviour, since %p
expects a void *
argument, and not a const char *
or a const char (*)[6]
. So the correct code is:
printf("%p\n%p\n", (void const *)"jesus", (void const *)&"jesus");
Upvotes: 6