nEAnnam
nEAnnam

Reputation: 1256

How an unassigned string is stored in memory and how to reference it?

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

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146191

C is a carefully specified language and we can make many observations about your examples that may answer some questions.

  1. Character literals are stored in memory as initialized data. They have type array of char.
  2. They are not necessarily strings because nul bytes can be embedded with \0.
  3. It is not required that identical character string literals be unique, but it's undefined what happens if a program tries to modify one. This effectively allows them to be distinct or "interned" as the implementation sees fit.
  4. In order to make that last line work, you need:

    char (*ptrToString)[] = &"jesus"; // now not an ERROR

Upvotes: 1

Kerrek SB
Kerrek SB

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

Related Questions