-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!

  • 1
    Maybe have a look at https://stackoverflow.com/questions/5935933/dynamically-create-an-array-of-strings-with-malloc –  Nov 15 '19 at 18:32
  • Also have a look at [a list of helpful C resources](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Mode77 Nov 15 '19 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. – Weather Vane Nov 15 '19 at 18:35
  • This question, or a variant of it, gets asked multiple times a day. Please search before asking! – dandan78 Nov 15 '19 at 19:00
  • Does this answer your question? [How to read the content of a file to a string in C?](https://stackoverflow.com/questions/174531/how-to-read-the-content-of-a-file-to-a-string-in-c) – dandan78 Nov 15 '19 at 19:01
  • @WeatherVane i made some changes but i'm still segment faulting. Thanks for the suggestion regarding the buffer but as a start i will only use sizes below "maxlength". – user12379675 Nov 15 '19 at 19:06
  • @dandan78 I'm not having problems reading data from a file, the problem is storing it in the manner i want. I did not find those examples useful, I'm sorry. – user12379675 Nov 15 '19 at 19:09
  • 1
    I don't know if it accounts for the segfault, but in the second loop `i < maxLines` should be `j < maxLines`. – Weather Vane Nov 15 '19 at 19:21
  • There is no need to cast the return of `malloc`, it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714) – David C. Rankin Nov 15 '19 at 19:25
  • @WeatherVane yeah that fixed it. But that was a silly mistake, your input that i need to allocate memory earlier was very important. thanks. – user12379675 Nov 15 '19 at 19:29

1 Answers1

1

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

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