Good day...

void main() { int a,b,c; int *A, *B; a = 3; b = 5; A = &a; B = &b; c = (A - B);// ??? printf("c=%d\n", c );//Vs 2015 выдает 3...Почему? printf("num1 = %d num2 = %d\n", *(B + c), *(A - c)); } 

I do not understand this action, or rather, because this is the subtraction of addresses and the difference is returned to the int? But after all, they do not have to be near, then I don’t understand where the number 3 comes from ...?

  • one
    The difference of pointers by 3 is the difference of addresses by 3 * sizeof(int) in this case. - insolor
  • why 3? Where did this number come from? So based on your comment with should get 12? (3 * 4)? - Biohazard
  • In my opinion, this is indefinite behavior. You can subtract pointers only within a single array. ru.stackoverflow.com/a/477313/235436 - Kirill Malyshev
  • I agree, more precisely, with the array it is much more understandable why this is being done, but in this case what is the point? The question is taken from the exam on C, which means there is some point, because then comes the second print ... but I can't understand what is (A - B) .... for starters .... - Biohazard
  • @Biohazard, well, here ideone.com/DvKIzL produces -1. After all, it is logical that a and b will follow each other in memory. In your case, the variable a, apparently, sits in memory 3 * sizeof (int) bytes further in memory than b. This is an indefinite behavior, it is not known in advance how the compiler will allocate variables in memory. This is guaranteed only in arrays. - Kirill Malyshev

2 answers 2

what is it done for, but in this case what is the point? ... because the second print goes further ... but I can't understand what it is (A - B)

The meaning of the operation of subtracting pointers in this example is to demonstrate the complementarity of the subtraction operation in relation to the operation COMPLEX. See what happens in the second printf statement:

 *(B + c) == *(B + (A - B)) == *(B + A - B) == *(A) == *А *(A - c) == *(B - (A - B)) == *(B - A + B) == *(В) == *В 

Beautiful trick - and nothing more :-)

    In C, it is allowed to subtract from each other only pointers to the elements of the same array (and to an imaginary element after the last element of the array). The result of this subtraction is the signed number of array elements between these pointers.

    Subtract from each other pointers to two independent variables - as in your case - indefinite behavior. There is no point in this subtraction.