In C, why does (int *) & x [k] work the same way as (int *) x [k] for a 2-D array x?

In the following code

 int x[2][3] = {{1,2,3},{4,5,6}};
 int* y1 = (int*)x[1];
 int* y2 = (int*)&x[1];

 int i;
 for(i=0; i < 3 ; i++)
 {
  printf("%i %i\n",y1[i],y2[i]);
}

why do y1 and y2 point to the same data?

I would think that x [1] is a pointer to the second row of data, so y1 should be the right way to access it. The expression & x [1] gets the address of the pointer to the second row of data, so why does y2 even work?

+3
source share
3 answers

Given an ad

int x[2][3] = {{1,2,3},{4,5,6}};

x[1] - "3- int". sizeof & , , " T" - .

,

int *y1 = (int *) x[1];

; x[1] int *, y1 x[1][0].

int *y2 = (int *) &x[1];

x[1] address-of &, int *. &x[1] " 3- int" int (*)[3]. , T T. , , , ; , , - .

, x[1] &x[1] ( ), , , ++ --.

,

int *y1      =  x[1];
int (*y2)[3] = &x[1];
+4

, x[1] - , . , - :), , :

int a[10] = {0};
assert(( int* )a == ( int* )&a);

0:

: int a[XXX]; sizeof( int ) * XXX. , a , a . (, , ). , , . () . , a , &a a.

, a , .

. , : "Expert C Programming Deep C Secrets"

+2

Since the 2D array does not store the actual pointer for each row. Only the address of the first element is stored on the stack. Because the array xhas a fixed known size, offsets are calculated at compile time.

The expression (int*)&x[1]lowers the array to the pointer, returning the same value.

The expression x[1]returns the address of the value 4in memory. Using the operator and you request the address of the address of the value 4, which does not make much sense in this case.

+1
source

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


All Articles