1

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?

2
  • 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. Commented Jun 18, 2023 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. Commented Jun 18, 2023 at 19:41

1 Answer 1

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 ^^^^^^^^ 
Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't it be *(*(x1+i)+j) -> x1[i][j] ?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.