0

&array[0] and &array[2] individually print the right values, which is the address of array[0] and array[2] respectively. However, when I subtract the two, 2 is printed instead of 8 which is the difference of the two addresses.

What are the relevant parts of the C standard that explain why the output is 2 and not 8?

Adapted from http://fabiensanglard.net/c/index.php

#include <stdio.h>

int main() {
    int array[] = {41,1821,12213,1645,20654} ;
    int* pointer = array;

    printf("%d %d %d %d\n", sizeof array, sizeof pointer, sizeof(int*), sizeof &array[2]);
    printf("%ld %ld %ld %ld\n", sizeof array[0], sizeof &array, array[0], &array[0]);
    printf("%ld %ld %ld %ld\n", sizeof array[2], sizeof &array, array[2], &array[2]);
    printf("%d\n", (&array[2]) - (&array[0]));

}
user2698
  • 315
  • 1
  • 3
  • 8
  • `x+1` is the next entry in the array that `x` points to an element of. Subtraction works in a similar manner; `(x+1) - x` is `1` (not `4`) – M.M Aug 21 '18 at 01:11
  • technically you're getting UB. [Pointers must be printed using `%p`](https://stackoverflow.com/q/9053658/995714), [`sizeof` (which returns `size_t`) must be printed using `%zu`](https://stackoverflow.com/q/940087/995714), and [subtracting 2 pointers produce a `ptrdiff_t` which must be pringed using `%td`](https://stackoverflow.com/q/7954439/995714) – phuclv Aug 21 '18 at 02:29

0 Answers0