Storing variables and dereferencing them

Based on the following snippet in C

int c1,c2;
printf("%d ",&c1-&c2);

Output : -1
  • Why this code does not return a warning that the% d format expects an int, but it receives (void *) instead.
  • Why does it return -1 as an answer (and not 1)? Even if he subtracts the addresses, it should be -4, not -1. When I change the printf statement to printf("%d ",&c2 - &c1), I get 1, not any random value! Why?
  • If I modify the printf statement as printf("%d ",(int)&c1 - (int)&c2)am, do I cast the address to an integer value? Does this mean that the value of the address stored as hex is now converted to int and then subtracted?
+4
source share
4

1) int. - - ( ptrdiff_t). , , .

2) , undefined. .

3) . "" . / ( ). . (hex/dec/oct/...).

+4

undefined.

C99 6.5.6 Additive, ( ):

, , ; . , type ( ) ptrdiff_t, . , undefined.

, undefined, .

printf ptrdiff_t %td, undefined, .

+1

1) printf, , , . undefined, .

2) , -4, . , . , c2 (&c1 + 1).

3) (int)&c1 c1 int. , , undefined, , int , . (int 32 64- ). intptr_t int.

0

1) * - , . (). int.

2) , ;). :

int a[2];
a[0] = 3;
*(a + 1) = 5; // same that "a[1] = 5;"

"5" . :

*(a + 1 *sizeof(*a)) = 5; 

3) - . int! :

int a = 0xFF;
printf("%d\n", a); // print 255

, .

0

Source: https://habr.com/ru/post/1545374/


All Articles