I开发者_开发技巧s there any way how to malloc()
a 2D matrix in C? I have successfully tried malloc()
ing a 1D field, but in matrix I am getting errors.
float *mat2d = malloc( rows * cols * sizeof( float ));
to access a value from the matrix use this adressing scheme:
float val = mat2d[ x + y * cols ];
If the size of the array isn't known at compile time you have to use a loop to allocate memory for each row.
Here's some sample code I found:
double** allocate2D(int nrows, int ncols) {
int i;
double **dat2;
/* allocate array of pointers */
dat2 = malloc( nrows*sizeof(double*));
if(dat2==NULL) {
printf("\nError allocating memory\n");
exit(1);
}
/* allocate each row */
for(i = 0; i < nrows; i++) {
dat2[i] = malloc( ncols*sizeof(double));
}
if(dat2[i-1]==NULL) {
printf("\nError allocating memory\n");
exit(1);
}
return dat2;
}
From here
Be sure to change the data type from double to whatever you need.
精彩评论