-
2D dynamic array problem
I am in the process of converting a C++ program to C and have run into
a major problem with 2D dynamic arrays in C. The code I have posted
below is just a test, but it does not work.
What I am trying to do is read data from a file to figure out its
dimensions (width and height) and then allocate an array with those
values. I can get the dimensions just fine. I run into problems
feeding those values into the dynamic allocation of the array.
Ok heres the code...thanks in advance for the help!!!
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int h=0, ho=0, w=0, wo=0, counter_w=0, counter_h=0, width=0;
char ch;
FILE *input_file, *ouput_file; /* Input file pointer
/* GET WIDTH AND HEIGHT OF MATRIX FROM FILE*/
input_file = fopen("input.dat", "r");
if(input_file == NULL)
{
printf("can't open file \n");
return 1;
}
else
{
while((ch=getc(input_file)) !=EOF)
{
if(ch != '\n') /* Note: looking at white space also */
counter_w++; /* counter_w = total character count */
else
counter_h++; /* counter_h for height only */
}
}
width = ((counter_w)/16)/(counter_h); /* calculates width */
/* '16' comes from fixed
width of values + white space */
printf("width = ");
printf("%d", width);
printf("\n");
printf("height = ");
printf("%d", counter_h);
printf("\n");
h = counter_h;
ho = counter_h;
w = width;
wo = width;
fclose(input_file);
/* DYNAMICALLY ALLOCATE ARRAY */
double **test;
test = (double **)malloc(ho * sizeof(double *));
for(i=0; i<ho; i++)
test[i] = (double *)malloc(wo * sizeof(double));
/* END DYNMAICALLY ALLOCATING ARRAYS */
free(test);
return 0;
}
[code][/code]tagged by Salem
-
-
This is C, not C++. As such, unless you're running a C99 compiler, you need to declare all variables at the start of the function or scope.
Next, there is no reason to typecast the return value of malloc. You can, there is just no point in it.*
Finally, you can't just free the entire array in one shot. You must free each "row" first, then the rest of the array can be freed. (Free using a loop.)
Quzah.
*Some people debate this, but this is neither the time nor the place. Search the forums if you disagree.
-
You're better off allocating the entire multidimensional array in one go -- IE multiply the number of rows by the number of columns and allocate an arrow of that length. Then, for accessing the array just multiply the row that you are trying to access times the number of columns in the array plus the column you are trying to access. That way you prevent memory fragmentation and you can use standard pointer arithmentic through rows as though it were a regular multidimensional array (this is how arrays are allocated internally by C++ anyways, so you might as well be more accurate in your model).