-1

I'm trying to read a file and save the strings in an array using pointers, but I'm having problems. Can someone give me suggestions of what to do?

// not allowed to change these two rows
char **Lines;
Lines = (char**)malloc(sizeof(char*)*maxLines);

...

FILE *fp;
fp = fopen(fileName, "r");     // fileName already exists here
int i=0, j=0;

while(i<maxLines){
    Lines[i] = (char*)malloc(maxLength * sizeof(char)); 
    i++;
}

// No string will be longer than "maxLenght" so no buffer is used.
while(fgets(Lines[j] , maxLength, (FILE*) fp) != NULL && j < maxLines) 
{
        j++
}

I want to fill "Lines" with each string in the file. I keep getting segmentation fault. Thanks!

10
  • 1
    Maybe have a look at stackoverflow.com/questions/5935933/… Commented Nov 15, 2019 at 18:32
  • Also have a look at a list of helpful C resources. Commented Nov 15, 2019 at 18:34
  • 4
    You allocated an array of pointers (one for each line) but didn't allocate memory for any of them. You can read each line into a generous buffer first so you know how long it is, then allocate enough memory and copy it. Commented Nov 15, 2019 at 18:35
  • This question, or a variant of it, gets asked multiple times a day. Please search before asking! Commented Nov 15, 2019 at 19:00
  • 1
    I don't know if it accounts for the segfault, but in the second loop i < maxLines should be j < maxLines. Commented Nov 15, 2019 at 19:21

1 Answer 1

1

In your second while loop replace "||" with "&&".

The loop in this case continues to execute even when after maxlines has reached.

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

3 Comments

That was a silly mistake by me. thanks. I'm still getting segment faults tho :(
Now that you are using j for fgets, use j<maxlines. i is already at maxlines.
This silly issue and another issue with that WeatherVane solved fixed it. thanks!

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.