How does this pointer arithmetic work?

#include <stdio.h>

int main(void){
  unsigned a[3][4] = {
    {2,23,6,7},
    {8,5,1,4},
    {12,15,3,9}
 };
 printf("%u",*((int*)(((char*)a)+4)));
 return 0;
}

The output on my computer is the value of a[0][1]ie 23 . Can anyone explain how this works?

Edit: Rolling Back to the old yuckycode, exactly what I was introduced to: P

+3
source share
5 answers

So you have an array in memory:

2, 23, 6, 7, 8...

What this does is pass an array to char*, which allows you to access individual bytes, and it points here:

2, 23, 6, 7, 8...
^

Then it adds four bytes, transferring them to the next value (more on this later).

2, 23, 6, 7, 8...
   ^

Then he turns it in int*and casts it, getting the value 23.


There are three things in this code.

-, , unsigned 4 . (, + 4). ! + sizeof(unsigned), unsigned.

- int: unsigned, int. unsigned, int ( int .) , int ( INT_MAX), . unsigned*, .

, . %d, %u, . , int* , printf unsigned*, . , 3 .

: . , yuck.

+13

:

unsigned a[3][4] = {
    {2,23,6,7},
    {8,5,1,4},
    {12,15,3,9}
};

(, a 0x8000, endian-ness int):

0x8000  0  0  0  2
0x8004  0  0  0 23
0x8008  0  0  0  6
0x800C  0  0  0  7
0x8010  0  0  0  8
0x8014  0  0  0  5
0x8018  0  0  0 14
0x801C  0  0  0 12
0x8020  0  0  0 15
0x8024  0  0  0  3
0x8028  0  0  0  9

:

*((int*)(((char*)a)+4))
  • ((char*)a) char.
  • +4 4 (4 * sizeof(char))
  • (int*) int.
  • *, int.

, ( , int - , ).

+9

a . char * 4. 4 , sizeof ( ) , . int * , ( *). , , int unsigned .

2D- , .

+2

unsigned int 4. i.e sizeof ( ) == 4

4 , [ C Java/# ..].

. char *, 4 , .

+1

2- 3x4.

((char*)a) char. b.

((char*)a)+4matches b[4], it points to the 5ith element of the char array (you remember that aarays in C are based on 0). Or just the 5th byte.

When converting the array back to int, the element of i-ththe int array begins with i*4byte if sizeof(int) = 4. So, on the 5th byte, the second element of the int array starts from where your pointer points. The compiler receives 4 bytes starting at position 4 and says int. This is exactly [0] [1].

+1
source

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


All Articles