vpp
vpp

Reputation: 141

pointer arithmetic(pointing to arrays)

i've a small doubt in pointers, please help me out..

void main()
{
    int x[10],*px=x,*py;
    int i;
    py = &x[5], i = py - (px);

    cout << "\nThe value of px=x is:" << (int)px << "\n";
    cout << "x[0]\t" << (int)x << "\n";
    cout << "x[5]\t" << (int)&x[5] << "\n";
    cout << "\nThe value of i=py-px is\n";
    cout << i;
}

in the above program, you get the value of 'i' as the difference of the integer equivalent of the array(memory) divided by two(10/2=5).Why is it not just the difference ie, 10??

thanks in advance!!

Upvotes: 0

Views: 45

Answers (1)

twalberg
twalberg

Reputation: 62369

If you are trying to get the difference between two of the array elements using your pointers, you need to dereference the pointers:

i = *py - *px;

The way you have it written, you are calculating the difference between the two addresses, which should be 5, unless you cast your pointers to void *, in which case it would be 5 * sizeof(int) (not sure if you're on 32-bit or 64-bit system - the answer would be different).

Oh, and you're not initializing x[] anyway, so your results might be a bit ... random...

Upvotes: 1

Related Questions