1

I am trying to read a series of 8 integers from a file into an array then display those integers. I keep getting a segmentation fault the third time around, and I can't quite figure out what I am doing wrong.

struct aStruct {
    int a;
    int b;
    ...
};

typedef struct aStruct myStruct; 

while(fgets(line, MAX_LENGTH, file) != NULL) {
    int myArray[8] = {0};
    char* val = strtok (line," ,\n\t\r");
    while (val != NULL)
    {
        myArray[i] = atoi(val);
        i++;
        val = strtok (NULL, " ,\n\t\r");
    }

    myStruct foo;

    foo.a = myArray[0];
    foo.b = myArray[1];
            ...
}

The input file is structured like so:

0, 0, 1, 5, 0, 0, 0, 0
1, 0, 2, 5, 0, 0, 0, 0
2, 0, 3, 5, 0, 0, 0, 0
3, 0, 4, 5, 0, 0, 0, 0
4, 0, 5, 5, 0, 0, 0, 0

When tested with:

printf("myArray[0]: %d ", myArray[0]);

I get an odd output of 0 0

Where I believe it should be 0 1. Am I not initializing something correctly, or is my new syntax incorrect for the struct? I've tried a few different combinations, cant quite figure it out.

3
  • Compile with all warnings and debugging info (e.g. g++ -Wall -g) and use a debugger (e.g. gdb); also new is a C++ keyword (not a C one). So you should tag your question as C++ (and improve your code to be more genuine C++, probably using std::vector ..). Also show more code, notably declaration of myStruct ... Commented Nov 13, 2013 at 23:13
  • Sorry. I was unaware that new is a C++ keyword. I am trying to write this all in C, so perhaps I should switch that around. Commented Nov 13, 2013 at 23:18
  • Then your code is not C and should not compile with a standard C compiler (unless if new is some very weird macro, you should show its definition). Commented Nov 13, 2013 at 23:18

1 Answer 1

4

I think your problem here is in uninitialized or non reset i variable. Adding i = 0 inside your while-loop might help.

while(fgets(line, MAX_LENGTH, file) != NULL) {
    i = 0; // <<< reseting array index
    int myArray[8] = {0};
    char* val = strtok (line," ,\n\t\r");
    while (val != NULL)
    {
        //...
        i++;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I'm blind. I knew it was something small. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.