Reputation: 109
Say I declared an arrayint a[]={1,2,3,4,5};
, when I do (*(&a+1)-a)
, it prints 5
.
I came to know that *(&a+1)
takes me to the end of an array, and as sizeof(a)=20
.
So does pointer arithmetic takes me ahead of size of allocated container?
Also I am little bit confused on pointer arithmetic, why it prints 5
rather than 20
?
Upvotes: 0
Views: 87
Reputation: 409136
The result of pointer arithmetic is is in units of the dereferenced type.
If you have a pointer to an int
then the units will be in int
elements.
If you have a pointer to an int[5]
then the units will be in int[5]
elements, which are exactly 5 times as big.
Upvotes: 4
Reputation: 61
For your program above, a and &a will have the same numerical value,and I believe that's where your whole confusion lies.You may wonder that if they are the same,the following should give the next address after a in both cases,going by pointer arithmetic:
But it's not so!!Base address of an array (a here) and Address of an array are not same! a and &a might be same numerically ,but they are not the same type. a is of type * while &a is of type (*)[5],ie , &a is a pointer to (address of ) and array of size 5.But a as you know is the address of the first element of the array.Numerically they are the same as you can see from the illustration using ^ below.
1 2 3 4 5
^ // ^ stands at &a
1 2 3 4 5 ^ // ^ stands at (&a+1)
1 2 3 4 5 ^ //^ stands at a
1 2 3 4 5 ^ // ^ stands at (a+1)
Hope this will clear the doubts.
Upvotes: 1
Reputation: 166
So does pointer arithmetic takes me ahead of size of allocated container?
No. Not the "size of allocated container", but the size of the dereferenced type. sizeof(a)
is 20 because as an object the type of a
is int[5]
instead of int*
, and the type of &a
is int[5]*
. It will be clearer if I rewrite your example as below:
typedef int Int5[5];
Int5 a = { 1, 2, 3, 4, 5 };
Also I am little bit confused on pointer arithmetic, why it prints 5 rather than 20?
(*(&a+1)-a)
is 5 because in this case a
is interpreted as int*
.
Upvotes: 0
Reputation: 962
Pointer arithmetic is not same as arithmetic operation (addition/subtraction) between hexadecimal values. Following example demonstrates both.
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int * pintx = *(&a + 1);
int * pinty = a;
cout << "pintx = " << pintx << endl;
cout << "pinty = " << pinty << endl;
cout << "Pointer Arithmetic : Ans = " << (*(&a + 1) - a) << endl;
// Prints 5
cout << "Pointer Arithmetic : Ans = " << (pintx - pinty) << endl;
// Save as above, Print 5
cout << "Hexadecimal Subtraction: Ans = " << ((int)pintx - (int)pinty) << endl;
// Prints 20, as you expect
return 0;
}
Hope this helps.
Upvotes: 1