string - Issue with printing char *argv[n] after a function call in C -
int readoptions(char *argv[]){ file * infile; char line_buf[bufsiz]; int = 0, j = 0 ; infile = fopen("options","r"); if(!infile){ fprintf(stderr,"file read failure\n"); exit(2); } while( < 10 && fgets(line_buf,sizeof(line_buf),infile)!=0){ printf("line buf : %s",line_buf); argv[i] = line_buf; i++; } } int main(){ int j ; char *options[10]; for(j = 0 ; j< 10 ; j++){ options[j] = malloc(len * sizeof (char)); } readoptions(options); for(j=0; j<10 ; j++) printf("%s %d\n",options[j], j ); }
the problem see - program print last line read in file. mistake ? , missing important pointer concept code ?
every element of argv
points same line_buf
. use strdup()
create new strings instead (which later have free).
Comments
Post a Comment