0

I have the following to parse a csv file, and it works fine until i changed

(getfield(tmp, 12)); 

to

(getfield(tmp, ver)); 

Is the problem in function declaration ?

here is the code :

const char* getfield(char* line, int num) { const char* tok; for (tok = strtok(line, ";"); tok && *tok; tok = strtok(NULL, ";\n")) { if (!--num) return tok; } return NULL; } int main() { double frame_index[40][300]; int horz; FILE* fp = fopen("output.txt", "r"); char line[1024]; for (int ver; ver<20;ver++) { while (fgets(line, 1024, fp)) { char* tmp = strdup(line); frame_index[ver][horz] = atof(getfield(tmp, ver)); // works if "ver" was explicitly defined printf("AA %f\n", frame_index[ver][horz]); free(tmp); horz++; } rewind(fp); } } 
2
  • Please show a Minimal, Complete, and Verifiable example. Commented Mar 16, 2016 at 13:54
  • getfield() may return NULL. Need to test for that before calling atof(). Commented Mar 16, 2016 at 14:06

1 Answer 1

2

You never initialize the variable ver. For example you might want to change

for (int ver; ver<20;ver++) 

to

for (int ver=0; ver<20;ver++) 

Update The same with horz..

Sign up to request clarification or add additional context in comments.

6 Comments

still getting a segfault :(
shouldn't be initialization automatically ?
For automatic (local) variables? No.
tried initializing the variables to zero, no avail thou.
Then you have additional problems. For example you never check your file has no more than 300 lines. Also you don't check each line is correct format. You should add some error-handling. And I would avoid composite constructs negation/predecrement and the token manipulation inside the for statement.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.