char word[]="hi there"; //print address of string
word
is the name of an object called char array. It has an address and a size.
On this address, there is the first element, a char with the value 'h'
. The following letters follow at the next addresses, up to the last 'e'
. This one is followed with a 0 byte, the string terminator. So the total size of the array is 9: 8 given chars plus a 0 byte.
+--+--+--+--+--+--+--+--+--+
|h |i | |t |h |e |r |e |# | <-- # means NUL byte.
+--+--+--+--+--+--+--+--+--+
+--+--+--+--+--+--+--+--+--+
|68|69|20|74|68|65|72|65|00|
+--+--+--+--+--+--+--+--+--+
Here we have one specialty: &word
and word
point to the same address, but the size of what they represent is different. &word
points to the whole array, so sizeof(*(&word))
is 9, while word
points to the first character, so sizeof(*word)
is 1.
It is said that "word
decays into a pointer" to the first element.
As asked in the comments, note that this is slightly different from the case
char * wordptr = "hi there";
as the memory layout is the same, but the string lies in readonly memory, while the normal data segment contains a pointer pointing to that string. So &wordptr
, wordptr
and *wordptr
are completely distinct from each other: &wordptr
is a char **
pointing to data memory, wordptr
is a char *
pointing to RO memory (i.e., to the real string - to be exact, to the first character of the string) and *wordptr
is just the 'h'
at the beginning.
OTOH,
int a = 1; // print address of 1
a
is the name of an object called int
. It as well has an address and a size.
Its size is implementation-dependent, its memory layout as well. Let's take a little endian machine where the lowest byte comes first, and let's assume we have 4 bytes per int:
+--+--+--+--+
|01|00|00|00|
+--+--+--+--+
You can take the address of both of them with &word
and &a
and print them out:
printf("%p %p\n", &word, (void *)&a);
((void *)
is needed because on some implementations, the sizes of the pointers can vary, so in order to be on the safe side, we need to cast the pointer type.)
The term "address of 1" doesn't make sense; while the variable whose address you get with &a
holds the value 1, this is mere "coincidence": you may set a = 3
, and the address remains the same, while the value stored there changes. So it is indeed better to say "address of a variable corrently holding 1".