Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does subtracting an address reference work?

I think the value of z should be 40 because a[5] has 20 elements, and the space between it and a[3] also has 20 elements. However, the actual value of z is 2.

Can anyone explain this concept?

#include <stdio.h>

int main()
{
    int a[10][20];
    int z = &a[5] - &a[3];
    printf("%d\n", &a[3]); // the address information is 6421740
    printf("%d\n", &a[5]); // the address information is 6421900
    printf("%d\n", z);     // z value is 2. why?
}
like image 287
Creek Avatar asked Aug 24 '26 16:08

Creek


1 Answers

Pointer arithmetic is done in the units of the pointed-to type.

In this case a[5] and a[3] are both elements of an array of type int [20], and &a[5] and &a[3] both have type int(*)[20]. They are 2 array element apart, so the difference between them is 2.

It doesn't matter that the underlying type is also an array.

like image 105
dbush Avatar answered Aug 27 '26 21:08

dbush