Reputation: 3
hello i have to assign a matrix to a double pointer i wrote this code for simplify the things.
int main (int argc, const char * argv[])
{
int ** matrix;
//// initialize the matrix
matrix = malloc(sizeof(int *)*3);
for (int i=0; i<3; i++)
{
matrix[i] = malloc(sizeof(int)*3);
}
// initialize the 2-d array
int matrixx[][3] = { {1,3,4},{5,3,1},{24,5,1} };
for (int i=0; i<3; i++) {
///good kind of assignment
matrix[i] = &matrixx[i];
}
/// error how i fix it ?
matrix = &matrixx[0][0];
}
Upvotes: 0
Views: 2151
Reputation: 272487
You can't fix it. The type of matrix
is int **
. The type of &matrixx[0][0]
is int *
. These are incompatible.
Your "good kind of assignment" is the correct approach if you want to maintain the array-of-pointers mechanism. However, you have the syntax for it slightly wrong; it should be:
for (int i=0; i<3; i++) {
///good kind of assignment
matrix[i] = matrixx[i];
}
Also, you don't need the loop that does this:
for (int i=0; i<3; i++)
{
matrix[i] = malloc(sizeof(int)*3);
}
(You'll incur a memory leak as @Chris points out below as soon as you re-assign these pointers.) Unless, of course, your intention is to copy the contents of the matrix. In which case, your approach is definitely wrong.
[Note also that you're not calling free()
anywhere, which means you have a memory leak.]
Upvotes: 2