Addresses of two char pointers to different string literals are same
#include<stdio.h>
#include<string.h>
int main()
{
char * p = "abc";
char * p1 = "abc";
printf("%d %d", p, p1);
}
When I print the values of the two pointers, it is printing the same address. Why?
Whether two different string literals with same content is placed in the same memory location or different memory locations is implementation-dependent.
You should always treat p
and p1
as two different pointers (even though they have the same content) as they may or may not point to the same address. You shouldn't rely on compiler optimizations.
C11 Standard, 6.4.5, String literals, semantics
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
The format for printing must be %p
:
printf("%p %p", (void*)p, (void*)p1);
See this answer for why.
Your compiler seems to be quite clever, detecting that both the literals are the same. And as literals are constant the compiler decided to not store them twice.
It seems worth mentioning that this does not necessarily needs to be the case. Please see Blue Moon's answer on this.
Btw: The printf()
statement should look like this
printf("%p %p", (void *) p, (void *) p1);
as "%p"
shall be used to print pointer values, and it is defined for pointer of type void *
only.*1
Also I'd say the code misses a return
statement, but the C standard seems to be in the process of being changed. Others might kindly clarify this.
*1: Casting to void *
here is not necessary for char *
pointers, but for pointers to all other types.