7

a is array of integers, if I try to subtract the address value of &a[2] - &a[1] == ? what should the result be 4 or 1 ?

EDIT: see 4th comment on top answer here why he says 1 ?? this is why I'm confused I thought it will be 4

EDIT: here is a test

Community
  • 1
  • 1
disioe
  • 73
  • 4

6 Answers6

9

&a[2] is same as &(*(a + 2)) (i.e (a + 2)) and &a[1] is same as &(*(a + 1)) (i.e. (a + 1)). So answer will be 1.

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
  • Thank you very much, I get it now. It was in the thread I read too but somehow I didn't get it. Thanks again for your help. – disioe May 24 '11 at 05:48
6

Pointer subtraction gives you the difference in elements, not bytes. It does not matter what the element type of the array is, the result of &a[2] - &a[1] will always be 1, because they are 1 element apart.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
4

It is always 1. The pointer arithmetics are not concerned with the number of bytes that each element has, and this is very useful. Compare these:

ptr++;  // go to the next element (correct)
ptr += sizeof *ptr;  // go to the next element (wrong)

When you work with arrays you are usually interested in the elements, not in the bytes comprising them, and that is why pointer arithmetics in C has been defined this way.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
3

The difference must be 1. When you compare pointers you will always get the difference of elements.

harper
  • 13,345
  • 8
  • 56
  • 105
2

Since this is C++, I'm going to assume that you have not overridden the & or * operators on whatever type a is. Minding that, the following is true:

&a[2] - &a[1]
(a + 2) - (a + 1)
a + 2 - a - 1
2 - 1
1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

A couple of the answers here (deleted since this answer was posted) clearly had byte* in mind:

    int a[10];
    byte * pA2 = (byte*)&a[2];
    byte * pA1 = (byte*)&a[1];
    int sz1 = &a[2] - &a[1];
    int sz2 = pA2 - pA1;
    CString msg;
    msg.Format("int * %d, byte * %d\n", sz1, sz2);
    OutputDebugString(msg);

output is:

     int * 1, byte * 4

Two addresses but depending on the declaration of the variable the addresses are stored in, the difference between the two can be 1 or 4.

sean e
  • 11,792
  • 3
  • 44
  • 56
  • 1
    That was my problem, as the question was not in code, I read the question as what is the difference between two addresses, not in terms of "pointer arithmetic". – Jens May 24 '11 at 07:32