Reputation:
I did a google on that, and I realized that some say it can some say it cannot.
I would just like to verify.
For example
char gchararr1i[] = "testing 123"; // global char array init
char *gptr1i = "hello", *gptr2ui; // global char pointer init and un-init
float gfloati = 123.4; // global float var init
double gdoubleui; // global double var un-int
int main(int argc, char *argv[]) {
printf("\n Address of string literals \"testing 123\" = %p and \"hello\" = %p \n", gchararr1i, gptr1i);// output the addresses of string literals "testing 123" and "hello"
f1(10, -20, 30.3, 'A', 45.67);
exit(0);
}
Upvotes: 2
Views: 906
Reputation: 340188
You can take the address of a string literal, but you can't be certain that two string literals with the exact same contents will be at the same address (or that they won't have the same address). The compiler toolchain is free to do as it wishes in that regard.
The standard even permits one string literal to share memory with another. For example the address of "world"
might 'point into' the literal "hello world"
. I'm not aware of an implementation that does this, but I haven't checked for it either.
Upvotes: 7
Reputation: 153348
Are we able to print out the address for string literal?
Yes. A simple example to print out the address for a string literal.
printf("%p\n", (void *) "Hello Word!");
Output
0x100403055
The following prints out the address of the first element of gchararr1i[]
. This may or may not be the address of the string literal. The string literal may not even exist separately in code.
char gchararr1i[] = "testing 123";
printf("%p\n", (void *) gchararr1i);
Output
0x22caa0
The following prints out the address value of the pointer gptr1i
which happens to be the address of the string literal "hello"
.
char *gptr1i = "hello";
printf("%p\n", (void *) gptr1i);
Output
0x100403060
--
Detail: "%p
is only defined with printing void*
pointers. When printing object pointers other than void*
, cast to void *
first. @user3386109. Note: to print function pointers see this.
int x;
// printf("%p\n", x);
printf("%p\n", (void *)&x);
Upvotes: 5