space_voyager
space_voyager

Reputation: 2034

Why is my pointer giving back value at address directly?

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?

Upvotes: 0

Views: 70

Answers (2)

R Sahu
R Sahu

Reputation: 206607

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.

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66922

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.

Upvotes: 1

Related Questions