There are multiple problems in your code fragment:
- there are syntax errors, such as missing
;
%p
expects a void *
, but you provide a char **
and char *
values.
printf("%p", (void*)&s)
and printf("%p", (void*)&s[0])
will not produce the same output: the first will print the address of the pointer s
, whereas the second will print the address s
points to, ie: that of the string literal "David"
which is an array of 6 bytes containing the values 'D'
, 'a'
, 'v'
, 'i'
, 'd'
and '\0'
.
- the final 2 statements should print the address of the
a
and that of the v
in the same array.
char *s = "David";
defines a pointer variable s
and a global unnamed array of 6 bytes, and it initializes the value of s
with the address of the array.
If you define 2 variables this way:
char *s1 = "David";
char *s2 = "David";
You will have 2 different pointers s1
and s2
that may or may not point to the same global unnamed array. It is unspecified whether identical string literals produce the same or different objects at run time.
For gcc
and clang
, the above produces code equivalent to this:
static char const __unnamed_1[6] = { 'D', 'a', 'v', 'i', 'd', '\0' };
char *s1 = (char *)&__unnamed_1[0];
char *s2 = (char *)&__unnamed_1[0];