double** Make2DDoubleArray(int arraySizeX, int arraySizeY) {
double** theArray;
theArray = (double**) malloc(arraySizeX*sizeof(double*));
for (int i = 0; i < arraySizeX; i++)
{
theArray[i] = &(malloc(arraySizeY*sizeof(double)));
memset(&(theArray[i]), 0, arraySizeY*sizeof(double));
}
return theArray;
}
I need to make a 2D array with malloc
in C. I used the above method.
When I access the returned array (let's call it Matrix
) with Matrix[1,2] = 2.0;
it throws an error:
cannot convert 'double' to 'double*' in assignment
But I don't see why Matrix[1,2]
is a pointer and not a value? Matrix
is a pointer of pointers, and Matrix[i]
is a pointer to a list of double
s, so Matrix[i,j]
should be a double
and not a double *
!
Matrix[i, j]
is the item in Matrix
at the index i, j
, which is the result of the comma operator on the values i
and j
, which is just Matrix[j]
. You probably mean Matrix[i][j]
.
In addition to that:
Don't cast the return value of malloc
:
double** theArray = malloc(arraySizeX * sizeof(double));
You are using the wrong sizeof
; it's sizeof(double*)
:
double** theArray = malloc(arraySizeX * sizeof(double*));
This makes no sense; drop the &
:
theArray[i] = &(malloc(arraySizeY*sizeof(double)));
This is wrong; drop the &
again:
memset(&(theArray[i]), 0, arraySizeY*sizeof(double));
These lines are wrong:
theArray[i] = &(malloc(arraySizeY*sizeof(double)));
memset(&(theArray[i]), 0, arraySizeY*sizeof(double));
I am surprised the compiler didn't complain about taking the address of a temporary in the first call.
You need:
theArray[i] = malloc(arraySizeY*sizeof(double));
// ^^ Drop the &
memset(theArray[i], 0, arraySizeY*sizeof(double));
// ^^ Drop the &
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.