0

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!!

2
  • It sounds like you expect sizeof(int)=2. Can you explain why you would expect the result to be 10? Commented Feb 19, 2013 at 15:57
  • well, suppose you get the integer eqv of memory of x[5] as '-24' and x[0] as '-34'..then shouldn't px-py result in -24+34=10?? Commented Feb 19, 2013 at 16:05

1 Answer 1

1

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.