Reputation: 49
I have following sample of code:
#include <stdio.h>
int main(void)
{
char *text[2];
text[0] = "Hello";
text[1] = "World";
printf("Address of text[0]: %p\n", text[0]);
printf("Address of text : %p\n", text);
return 0;
}
The output of this program is:
Address of text[0]: 0x400694
Address of text : 0x7ffcac41b000
I am wondering why these addresses differ in length. Why is address of first pointer to char only 6 digits length?
Upvotes: 3
Views: 95
Reputation: 29724
printf("Address of text[0]: %p\n", text[0]);
prints the address of C string (the address first element of array points to), while:
printf("Address of text : %p\n", text);
prints the address of array's first element.
Upvotes: 0
Reputation: 28806
To get the address of the first item of the array text
, you'll have to use:
printf("Address of text[0]: %p\n", (void *)&text[0]);
In your question, you are printing the address of the first character of the string "Hello"
(in other words, of the content of text[0]), not the address of the first element of the array text
, i.e. not the address of text[0]
, just the address stored in text[0]
.
Upvotes: 0
Reputation: 46323
There is no difference in "address length", the difference is in the value.
In this particular case, I assume the text[0]
pointer points to a data segment that holds the compile time value "Hello"
, and the text
pointer points to a runtime address.
Since these are at different memory segments, they can be "very far" and so you get the output you see.
Upvotes: 3
Reputation: 61969
The first address is the address of "Hello", which is stored in your data segment.
The second address is the address of text[]
, which is stored in your stack.
These two areas of memory are far from each other, so one has many digits, the other has few digits.
Apparently, %p
renders only as many digits as necessary to represent the address.
Upvotes: 2