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?
x1is a single pointer and assigningx1 = 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.x1will store the address to the row ofy". The pointerx1doesn't have any elements; it only points toy.