NoName123
NoName123

Reputation: 303

Unexpected result when doing subtraction of addresses of array elements

I am on a x32-based processor where char = 1 byte, short = 2 bytes and int = 4 bytes.

When I create an array of type char with 20 elements in it, I expect to see 20 memory spaces allocated to that array with the addresses differing by only 1 byte because of the type of the array.

If I take two consecutive elements from the array and subtract their addresses, should I then not get 1 in this case?

And in the case of arrays with types short and int, I am expecting to get 2 and 4. This due to the fact that the short and int elements need be aligned in memory. short elements will be on even addresses (diff 2) and int elements will be on addresses divisible by 4.

Though, how come when I run the following code I get 1,1,1 and not 1,2,4?

I suspect I am missing some cruical detail when it comes to pointer arithmetics.

char vecc[20];
printf("%i\n", &vecc[1]-&vecc[0]);
    
short vecs[20];
printf("%i\n", &vecs[1]-&vecs[0]);
    
int veci[20];
printf("%i\n", &veci[1]-&veci[0]);

Upvotes: 2

Views: 79

Answers (2)

user15280715
user15280715

Reputation:

If you write the code in this way:

        printf("%i\n", (char*)(&vecs[1]) - (char*)(&vecs[0]));
        printf("%i\n", (char*)(&veci[1]) - (char*)(&veci[0]));

the output will be 2 and 4.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

Pointer subtraction yields the result as difference in the indexes, not the size of the gap between the addresses.

Quoting C11, chapter 6.5.6, (emphasis mine)

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. [...]

Upvotes: 5

Related Questions