Here is my code:
typedef struct { int** matrix; int rows; int cols; }intMat; intMat create_intMat(int rows,int cols,int matrix[rows][cols]){ intMat A; A.rows = rows; A.cols = cols; int** mat; mat = malloc(A.rows*sizeof(int*)); // Pointer for matrix rows for(int i=0;i<A.rows;i++) mat[i] = malloc(A.cols*sizeof(int)); // Pointer of each matrix row to a matrix column for (int i=0;i<A.rows;i++){ for (int j=0;j<A.cols;j++){ mat[i][j]=matrix[i][j]; } } A.matrix = mat; return A; } int main() { int mat[2][2] = {{1,2},{3,4}}; intMat A; A = create_intMat(2,2,mat); printf("%d\n",A.matrix[1][1]); return 0; } I'm a beginner to pointers and got the pointer part of the code from another forum. I don't get it, though. int** mat is a pointer to a pointer to an int, so if I call it as is then it should give me back gibberish address, not the int being pointed to. However, the printf statement returns 4, which is the value of the int being pointed to! How come this is happening?
[]operator. Remember thata[b]is defined to be equivalent to*(a+b), so when you writemat[1][1]you are doing*(*(mat+1)+1), which, as you see, is dereferencingmattwice, getting fromint **toint.