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][/code]tagged by SalemCode:#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; }



LinkBack URL
About LinkBacks


