parsing - C pass by reference "returns" incorrect content -
i want read values file using function , pass them main. file has specific format:
string double char
for example 2 lines:
blahblah 0.12 g
testtesttest 0.33 e
i have following program. although values printed correctly in function, in main few of them printed. rest 0.00000 , no character printed well. doing wrong?
#include<stdio.h> #include<stdlib.h> #include<string.h> int read_file(const char *filename, double **prob, char **sense); int main(){ double *iprob; char *sense; read_file("test.txt", &iprob, &sense); printf("main: %lf %c\n", iprob[0], sense[0]); return 0; } int read_file(const char *filename, double **prob, char **sense){ file *fp; char line[100], temp[80]; int = 0; fp = fopen(filename, "r"); if (fp == null){ fprintf(stderr,"file %s not found!\n", filename); return 0; } //*prob = (double *)malloc(sizeof(double) * 100); //*sense = (char *)malloc(sizeof(char) * 100); while( fgets(line, 100, fp) != null){ prob[i] = (double *)malloc(sizeof(double)); sense[i] = (char *)malloc(sizeof(char)); if ( sscanf(line, "%s %lf %c", temp, prob[i], sense[i]) < 3 ){ fprintf(stderr, "parsing error detected @ line %d!", i); fclose(fp); return 0; } else{ printf("%lf %c\n", *prob[i], *sense[i]); } i++; } fclose(fp); return 1; }
you use double pointer double
in functions, because want update pointer passed in main
.
the problem is, allocated array in *prob
, , therefore have address elements of array (*prob)[i]
.
*prob[i]
same *(prob[i])
. prob
pointer pointer; has 1 element, speak, index except 0 invalid here.
below correction of code:
- it reads in many entries there in file reallocating memory needed.
- it returns -1 on failure , number of items when successful, know how many items can safely address.
- you should
free
both pointers after use.
so:
#include <stdio.h> #include <stdlib.h> #include <string.h> int read_file(const char *filename, double **prob, char **sense); int main(){ double *iprob = null; char *sense = null; int i, n; n = read_file("test.txt", &iprob, &sense); (i = 0; < n; i++) { printf("main: %lf %c\n", iprob[i], sense[i]); } free(iprob); free(sense); return 0; } int read_file(const char *filename, double **prob, char **sense){ file *fp; char line[100]; int size = 0; int = 0; *prob = null; *sense = null; fp = fopen(filename, "r"); if (fp == null) return -1; while (fgets(line, sizeof(line), fp) != null) { char temp[80]; if (i >= size) { size += 8; *prob = realloc(*prob, size * sizeof(**prob)); *sense = realloc(*sense, size * sizeof(**sense)); if (*prob == null || *sense == null) { fclose(fp); return -1; } } if (sscanf(line, "%79s %lf %c", temp, &(*prob)[i], &(*sense)[i]) < 3) { fprintf(stderr, "parsing error detected @ line %d!", i); fclose(fp); return -1; } printf("%lf %c\n", (*prob)[i], (*sense)[i]); i++; } fclose(fp); return i; }
Comments
Post a Comment