For starters you shall use correct conversion specifiers in the function printf
. Otherwise the behavior of the function is undefined.
So these calls
printf("%d %d %s\n", &str1, str1, str1);
printf("%p %d %s\n", &str2, str2, str2);
are wrong because there is used the conversion specifier %d
with pointers.
My question is, is there a way to print address of array Goodbye using
the pointer *str2?
In fact the address of the array that corresponds to the string literal "Goodbye"
is the same as the address of the first character of the string literal.
char *str2 = "Goodbye";
However you can not obtain a pointer to the string literal using the pointer str2
.
What is the problem?
The pointer str2
knows nothing about whether it points to a single object of the type char
or to the first character of some array. It does not keep such an information.
Take into account that the array that corresponds to the string literal "Goodbye"
has type char[8]
. So a pointer that would point to the array shall have type char ( * )[8]
.
You could write for example
char ( *str2 )[8] = &"Goodbye";
In this case the pointer str2
indeed will have the address of the array. Otherwise having the pointer as it is defined in your example
char *str2 = "Goodbye";
you can not get the address of the array because as it was mentioned the pointer knows nothing about the array and its size.
On the other hand the value of the address of the first character of the string literal is equal to the value of a pointer to the string literal. That is if to consider the first declaration
char str1[] = "Hello";
then the expressions str1
and &str1
will yield the same value though the expressions have different types. The first one has the type char *
(if the expression is used in a context when an array designator is implicitly converted to pointer to its first element). And the second one has the type char ( * )[6]
. But the both values will be equal.:)
It is seem from the output (provided that you used correct conversion specifiers)
-1226226640 -1226226640 Hello