gln
gln

Reputation: 1031

Pointer to a matrix in c

in my c application I have this typedef:

typedef double mat[2][2];

this is my declaration of function:

aaa(mat bbb, mat ccc, mat * ddd)

in my code I want to compute the sum of each member in math and write the result in ddd. I did it over loops and this is the main line:

*ddd[i][j] = bbb[i][j] + ccc[i][j];

but I'm getting wrong result in ddd. when I remove the pointer from ddd, I get the right result, but since I want to return it to the user by pointer I want your help.

what is wrong in my code?

Upvotes: 2

Views: 346

Answers (4)

ob_dev
ob_dev

Reputation: 2838

[ ] have a higher precedence than * you should use parentheses.

(*ddd)[i][j] = bbb[i][j] + ccc[i][j];

Passing ddd as a pointer is not necessary.

aaa(mat bbb, mat ccc, mat  ddd)

ddd[i][j] = bbb[i][j] + ccc[i][j];

ddd is already a pointer to a matrix and the code above will work fine.

Upvotes: 1

Jason
Jason

Reputation: 32538

In C, arrays used as function arguments decay to pointers to the first member of the array and are therefore already passed by reference. So in your case, there is no need to pass an explicit pointer to the array, since a pointer-conversion is already taking place under-the-hood during compilation by the C-compiler.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258668

You're writing at the wrong address. It should be:

(*ddd)[i][j] = bbb[i][j] + ccc[i][j];

or simply change the prototype to

aaa(mat bbb, mat ccc, mat ddd)

since arrays decay to pointers anyway. ddd will be a copy, but the address it points to will be the same as the original.

Upvotes: 3

littleadv
littleadv

Reputation: 20282

Passing array is the same as passing the address of the first member. Since your type is an array, you don't need the * in the function definition.

Do:

aaa(mat bbb, mat ccc, mat ddd)
{
    // whatever
    ddd[i][j] = bbb[i][j] + ccc[i][j];
    // whatever else
}

And you're good

Upvotes: 1

Related Questions