0

So, this code was given by my teacher and it works fine, but I am confused as to why it is int (*x1)[3]; and not int (*x1)[2]; as y has 2 rows only. I think that each element of this array x1 will store the address to the row of y so only two such elements are required and not 3. Kindly help me. Thank you

int main(){
int (*x1)[3];
int y[2][3]={{1,2,3},{4,5,6}};
x1 = y;
for (int i = 0; i<2; i++)
  for (int j = 0; j<3; j++)
    printf("\n The X1 is %d and Y is %d",*(*(x1+i)+j), y[i][j]);
return 0;
}

I tried running this code and it is working fine. I don't understand how it is working though. Like what is going on internally? How is the memory being allocated?

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Sj2704
  • 1
  • Note that `x1` is a single pointer and assigning `x1 = y;` only sets that pointer. No data is copied. This variable's size is the size of a pointer. It only points to an object with rows of the same length (3). For a 2-D array, C doesn't really care how many rows there are (except when allocating the memory). It's up to the programmer not to exceed them. – Weather Vane Jun 18 '23 at 19:34
  • ... *"each element of this array `x1` will store the address to the row of `y`"*. The pointer `x1` doesn't have any elements; it only points to `y`. – Weather Vane Jun 18 '23 at 19:41

1 Answers1

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

Every element in y is an int[3] and y has 2 such elements. This declares a pointer to one such element:

int (*x1)[3];

And in this, y decays into a pointer to the first element which is why the assignment works:

x1 = y;

Suggestion for making it a little easier to read:

x1 = y;
for (int i = 0; i < 2; ++i, ++x1) // step x1 here
    for (int j = 0; j < 3; ++j)
        printf("\n The X1 is %d and Y is %d", (*x1)[j], y[i][j]);
// and dereferencing it becomes nicer here    ^^^^^^^^
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • shouldn't it be `*(*(x1+i)+j)` -> `x1[i][j]` ? – tstanisl Jun 26 '23 at 09:55
  • @tstanisl That works too if we skip stepping the `int[3]` pointer in the outer loop. I thought it would prove more useful to step the pointer to show what it is since OP thought it should be an `int[2]` pointer. – Ted Lyngmo Jun 26 '23 at 10:18
  • OP however never reacted to the answer in any way so I'm not sure if I made anything clearer :-/ – Ted Lyngmo Jun 26 '23 at 10:20