2

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]);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
NoName123
  • 273
  • 3
  • 12

2 Answers2

5

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. [...]

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.

  • You can cast every type of pointer to char pointer in C. The result of substraction of pointers is the difference between the addresses divided by the size of the type of the pointer. We know that the sizeof(char) is 1. –  Apr 16 '21 at 16:46