1

I am just confused with the output which I got for the following code :

int arr[] = {10,20,30};
cout<<&arr[1]<<"\t"<<&arr[0]<<"\t"<<&arr[1] - &arr[0];

the output which I got was like

0046F7A0    0046F79C    1

I want to know why the difference between the address gave 1 ( I expected 4)...? Is it something to do with pointer subtraction..?

3 Answers3

4

Yes, this is the result of pointer arithmetic. This is the same reason why arr + 1 would point to arr[1]. Pointer arithmetic is only well-defined when both pointers point to elements in the same array. If two such pointers, P and Q, point to array locations i and j, then P-Q = i-j.

Also, if you look at the differences of the actual addresses printed, they match your expectations - the difference is 4.

Pradhan
  • 15,095
  • 3
  • 39
  • 56
0

You are correct, this has to do with pointer arithmetic. Subtracting two int pointers gives you the difference between them measured in sizeof (int) units. You can get the difference in plain bytes by casting your pointers to char pointers, as chars are guaranteed to be of size 1.

uint arr[] = {10,20,30};
cout << &arr[1] << "\t" << &arr[0] << "\t" << (char*)&arr[1] - (char*)&arr[0];

Output:

0x23fe44        0x23fe40        4
ApproachingDarknessFish
  • 13,013
  • 6
  • 35
  • 73
-1

0046F7A0 - 0046F79C is actually 4 but &arr[0]-&arr[1] = (0046F7A0 - 0046F79C)/sizeof(int= 4 bytes) because subtracting two pointers gives you the number of elements between them.

David Arenburg
  • 87,271
  • 15
  • 123
  • 181
faro_hf
  • 99
  • 1
  • 2