0

I can't seem to understand why I am getting this error. It seems bizarre to me that subtraction works just fine (producing -3) while addition gives me an error.

Why is this the case?, Shouldn't addition return (0x00000001 + 0x00000002 = 0x00000003)?

#include <stdio.h>

int main()
{
    int* x = NULL;
    int* y = NULL;

    // error: invalid operands to binary + (have ‘int *’ and ‘int *’)
    int z = &x[0] + &x[3];

    // but this works fine
    int z = &x[0] - &x[3];

    printf("0x%08x\n", x);
    printf("0x%08x\n", &x[0]);
    printf("%d", z);

    return 0;
}
mrflash818
  • 930
  • 13
  • 24
AlanSTACK
  • 5,525
  • 3
  • 40
  • 99
  • 9
    What do you think addition would give you? – iBug Dec 13 '17 at 01:25
  • 1
    https://stackoverflow.com/questions/25667580/addition-of-two-pointers-in-c-or-c-not-supported-why – pm100 Dec 13 '17 at 01:31
  • if you absolutely need this, you can cast them to `int` and then do the addition. `(int)&x[0] + (int)&x[3]`. But agreed with iBug, I cannot see a situation where this would be useful. – Yuchen Dec 13 '17 at 01:35
  • 1
    Subtraction of pointers is only specified for pointers in (or 1 after) the same _valid_ array. `&x[0] - &x[3];` is not a valid subtraction. As it gave the hoped for result is bad luck. – chux - Reinstate Monica Dec 13 '17 at 02:36

0 Answers0