0

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?

2
  • 1
    Actually, you are dereferencing it twice through the use of the [] operator. Remember that a[b] is defined to be equivalent to *(a+b), so when you write mat[1][1] you are doing *(*(mat+1)+1), which, as you see, is dereferencing mat twice, getting from int ** to int. Commented Feb 25, 2015 at 23:09
  • @MatteoItalia -- you should consider posting that as an answer rather than a comment. Commented Feb 25, 2015 at 23:13

2 Answers 2

1

A.matrix is a pointer to a 2 pointers, which each point to 2 ints.
A.matrix[1] gets the second of those pointers - a pointer to 2 ints.
A.matrix[1][1] gets the second of those ints.

Sign up to request clarification or add additional context in comments.

Comments

0

When you use:

int i; int* p = &i; 

or

int* p = malloc(sizeof(int)); 

p points to a single integer.

When you use:

int array[10]; int *p = array; 

or

int *p = malloc(sizeof(int)*10); 

p points to an array of 10 integers.

Similarly, a variable declared with:

int** mat; 

can point to one int* or an array of int*s.

In your case, mat points to an array of 2 int*, each of which points to an array of 2 ints.

That makes use of mat[1][1] perfectly valid code.

1 Comment

in your code int *p = array; should it not instead be int *p = &array;? And thanks for the explanation!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.