LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

dinamically allocate 2d array

I'm trying to dinamically allocate a 2 dimensional array like this:

double **array;

//create array
array = (double **) malloc ( LEN1 );
for (i = 0; i < 8; ++i )
array[i] = (double *) malloc ( 10 );


//fill the array
for (i = 0; i < 8; ++i) {
for (j = 0; j < 10; j++) {
array[i][j] = someValue;
}

The problem is that I don't get the expected size, always creates a smaller array so index goes out of bounds while filling it.
What's wrong in this code?

Thank you.
Image Hosted by ImageShack.us
0 Kudos
Message 1 of 2
(3,082 Views)
Your problem is most likely that the argument to malloc is in bytes rather than elements (malloc has no idea that you are allocating doubles.

When you call malloc, you should generally do something like:
array = (double**) malloc (sizeof(double*)*length1);

or
array[i] = (double *) malloc (sizeof(double)*length2);

Regards,
Ryan K.
0 Kudos
Message 2 of 2
(3,078 Views)