David Young
David Young

Reputation: 129

Initializing a matrix with a pointer to pointer?

Suppose I have initialised a matrix with the following:

double** m = (double**) calloc(count, sizeof(*double));
for (int i = 0; i < count; i++){
        *(m+i) = (double*) calloc(count, sizeof(double));
}

Now I want to pass this matrix to a function with the following declaration:

double func(void* params)

Is the following the correct way to get the matrix from params:

double** m = *(double**) params;

Then I can just access elements in m normally? E.g.

double a = m[1][2];

Upvotes: 1

Views: 401

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

For starters this code snippet

double** m = (double**) calloc(count, sizeof(double));
                                      ^^^^^^^^^^^^^
for (int i = 0; i < count; i++){
        *(m+i) = (double*) calloc(count, sizeof(double*));
                                         ^^^^^^^^^^^^^^^  
}

is invalid.

I think you mean

double** m = (double**) calloc(count, sizeof(double *));
                                      ^^^^^^^^^^^^^^^^
for (int i = 0; i < count; i++){
        *(m+i) = (double*) calloc(count, sizeof(double));
                                         ^^^^^^^^^^^^^  
}

This function declaration

double func(void* params);

does not make sense. The size of the array (matrix) is not known. You should specify the size.

The function can be declared like

double func(void* params, int size );

and within the function you can write

double **a = params;

and use expressions like

a[i][j]

where i and j belong to the range [0, count)

and call the function like

func( m, count );

Upvotes: 1

M.M
M.M

Reputation: 141658

You didn't say how you call the function. But if the call is func(m) then the code in the function would be double** m = params;

The code you posted is a constaint violation (assign double * to double **).

Upvotes: 1

Related Questions