C ++: & a [2] - & a [1] ==?

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

EDIT : see 4th comment on top answer here , why does it say 1 ?? that's why i'm embarrassed i thought it would be 4

EDIT : here is test

+7
source share
6 answers

&a[2] matches &(*(a + 2)) (iee (a + 2) ) and &a[1] matches &(*(a + 1)) (ie (a + 1) ) . Therefore, the answer will be 1.

+9
source

Subtracting a pointer gives you the difference in elements, not in bytes. It doesn't matter what the type of the element is, the result &a[2] - &a[1] will always be 1, because they are divided into 1 element.

+6
source

It is always 1. Pointer arithmetic is not related to the number of bytes that each element has, and this is very useful. Compare them:

 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 the bytes that contain them, and that is why pointer arithmetic in C was defined this way.

+4
source

The difference should be 1. When you compare pointers, you will always get the difference between the elements.

+3
source

Since this is C ++, I assume that you have not redefined the & or * operators for any type a . Note that the following is true:

 &a[2] - &a[1] (a + 2) - (a + 1) a + 2 - a - 1 2 - 1 1 
+2
source

A few answers here (deleted after this answer was posted) explicitly meant bytes *:

  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); 

:

  int * 1, byte * 4 

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

+1
source

All Articles