My_Pointer_substraction

Hello.
Why do I get 4 printed in the following code snippet?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int x[]={1, 4, 8, 5, 1, 4};
int*ptr, y;
int main( int argc, char *argv[] )
{
    ptr = x+4;
    cout << x << endl;
    cout << ptr << endl;
    y = ptr - x;
    printf("y=%d", y);
    while(1);
    return 0;
}

LOOK...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int x[]={1, 4, 8, 5, 1, 4};
int*ptr, y;
int main( int argc, char *argv[] )
{
    ptr = x+4; // <== HERE...
    cout << x << endl;
    cout << ptr << endl;
    y = ptr - x; // <== AND HERE!
    printf("y=%d", y);
    while(1);
    return 0;
}
Last edited on
I mean whyit is not 16
For y? Because you assign it to ptr - x, where ptr is x + 4.
End result is 4.

Note that y is not a pointer, just a regular int. When you do pointer subtraction it'll return the distance between the two addresses, but it'll divide it by the size of the type pointed to.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int x[]={1, 4, 8, 5, 1, 4};
int*ptr, y;
int main( int argc, char *argv[] )
{
	ptr = NULL;
	y = x-ptr;
	std::cout<<x<<'\n'<<y;
    while(1);
    return 0;
}

Note that if you run this the value of y will be exactly x/4.
See the "Pointer arithmetic" section of "Pointer craft"
http://www.cplusplus.com/articles/z186b7Xj/

Basically. when you add an integer 'n' to a pointer, the pointer is moved x times the size of the pointed to type.

e.g. as an int is 4 bytes (for most 32-bit systems), adding 2 to an int* variable increments the address by 2 x 4 = 8 bytes.

And then you take the difference of two pointers of the same type, it's the number of that variable type that fit into the space that is returned, not the number of bytes (unless it's a byte pointer, of course)
Topic archived. No new replies allowed.