arrays - How to use more than one dynamic allocation on C programming? -
i'm making program reads 2 sets of data (float) 2 different .txt files, , transfers these data 2 different arrays, used in further calculations. however, when try use dynamic allocation more once, goes wrong , data seem not stored in array.
the following simplified program seems working fine:
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float *vara; int n = 0; int *counter; int i; file *input1; input1 = fopen("c:\\users\\...test.txt","r"); vara = (float*)calloc(20001, sizeof(float)); for(i = 0; < 20001; i++) { fscanf(input1,"%f",&vara[i]); printf("%f\n",vara[i]); } free(vara); fclose(input1); return 0; }
it shows data stored in array vara. however, if introduce new array count number of lines in file (which necessary further calculations), value 0.000000 every array element:
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float *vara; int n = 0; int *counter; int i; file *input1; input1 = fopen("c:\\users\\...test.txt","r"); counter = (int*)calloc(100000, sizeof(int)); while(fscanf(input1,"%f",&counter[n]) != eof) { n++; } free(counter); printf("n = %i\n", n); vara = (float*)calloc(n, sizeof(float)); for(i = 0; < n; i++) { fscanf(input1,"%f",&vara[i]); printf("%f\n",vara[i]); } free(vara); fclose(input1); return 0; }
i know can avoid using array count number of lines. point every time use array, purpose, same result. instance, if don't use array count number of lines, make 1 store other set of data, 1 of these arrays won't present data after reading. tried modify program several times in order find source of such behavior, without success.
(at least) 2 major problems: first,
counter = (int*)calloc(100000, sizeof(int)); while(fscanf(input1,"%f",&counter[n]) != eof) { n++; } free(counter);
is saying "grab me chunk of memory, fill data read file, throw away without ever using it." not intended. then,
vara = (float*)calloc(n, sizeof(float)); (i = 0; < n; i++) { fscanf(input1,"%f",&vara[n]); printf("%f\n",vara[n]); } free(vara);
which says, "grab big chunk of memory, read data after end of file read from, put there, throw away."
if want read data same file again, you'll have close reopen (or "seek" start). , if want it, you'll have before free()ing memory loaded into.
Comments
Post a Comment