Reputation: 1336
ptr
can be assumed to have the address 1000:2000
code:
int ptr[2];
printf("%p %p %p",&ptr+1,ptr+1,ptr);
What will be the output of above code?
What I tried:
As I don't know how to interpret/convert 1000:2000
into an address, I tried manually.
I tried this by considering ptr
's address as 10000+2000=12000
So, &ptr=12000
and &ptr+1=12000+sizeof(int)
ptr
is the address of first element being pointed, similarly ptr+1
is the second element's address
Is this right?
How can I test this?
Upvotes: 0
Views: 88
Reputation: 91017
This is simple pointer arithmetics if you know the types.
int ptr[2];
printf("%p %p %p",&ptr+1,ptr+1,ptr);
ptr
is the array's name which decays to a pointer to the first element. Let it be 1000:2000
, if it was an old book.
So ptr+1
is one element further, thus, if int
has size 4, 1000:2004
. (Probably int
has size 2 in this book, so it would be 1000:2002
.)
&ptr
, however, is a pointer to the array. It points to the same place - 1000:2000
-, but to a larger item: twice as large. So adding 1, the result is incremented by the size of two integers, thus 8 resp 4. So &ptr+1
gets you 1000:2008
resp. 1000:2004
as answer.
Upvotes: 1
Reputation: 2857
+-------------------------------------+
|{ ptr[0] ptr[1] } {ptr1[0],ptr1[1]} |
| ^ ^ ^ |
| | | | |
| ptr ptr+1 | |
| | | |
| &ptr &ptr+1 |
+-------------------------------------+
It is easy to understand ptr
pointer the first address item of this array, ptr+1
pointer the second item of array. &ptr
,it is a pointer point a int array[2]
int is a int (*x)[2]
,so &ptr +1 means the address move a int array[2]
.
Here is a test code:
#include <stdio.h>
int main()
{
int ptr[2];
int i;
for (i =0; i <3; ++i)
printf("ptr + %d is : %p\n",i,&(ptr[i]));
printf("\n&ptr +1 : %p\nptr+1 : %p\nptr : %p\n",&ptr+1,ptr+1,ptr);
}
Screen Print
ptr + 0 is : 0xbf892614 <---the same as ptr base address
ptr + 1 is : 0xbf892618 <---the same as prt+1 4 byte add
ptr + 2 is : 0xbf89261c < --the same as &ptr +1 4 byte add
&prt +1 : 0xbf89261c
ptr+1 : 0xbf892618
ptr : 0xbf892614
Upvotes: 1