Did you include stdlib.h?
There is no need (and some risk) to casting the return from malloc().
You have (apparently), allocated a pointer to a 2D array, but you have not yet allocated the pointers for each row of the array:
Code:
for(i = 0; i < NumberOfRowsYouWant; i++)
array[i] = malloc(columnsYouHave * sizeof(float)); //not float * for this one
When you are done, free the row pointers first, and then the array pointer, (IOW, free them in reverse of the order you created them in).
An example:
Code:
/* dynamically creates a 2D array of pointers, in C */
#include <stdio.h>
#include <stdlib.h>
//void allocate2D(double **dat2, int nrows, int ncols);
double** allocate2D(int nrows, int ncols);
int main() {
int i,j, rows, cols;
double **dat;
printf("\n\n\n How many rows do you want?\n ");
scanf("%d", &rows);
(void) getchar();
printf(" How many columns do you want?\n ");
scanf("%d", &cols);
(void) getchar();
dat = allocate2D(rows, cols);
for(i=0;i<rows;i++) {
for(j=0;j<cols;j++) {
dat[i][j] = i+j;
}
}
for(i=0;i<rows;i++) {
for(j=0;j<cols;j++)
printf("\n%.3lf", dat[i][j]);
}
for(i=0;i<rows;i++)
free(dat[i]);
free(dat);
printf("\n\t\t\t press enter when ready");
(void) getchar();
return 0;
}
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;
}