1

I am trying to read from a file in C. My code is the following. It seems to read everything fine into the array, but when I try to print it, I get the error Segmentation fault (core dumped)

  FILE *fp;
   char * text[7][100];
   int i=0;

   fp = fopen("userList.txt", "r");

   //Read over file contents until either EOF is reached or maximum characters is read and store in character array
   while(fgets((*text)[i++],100,fp) != NULL) ;

   printf("%s", &text[0]);

   fclose(fp);

Can someone point me in the right direction?

I have tried reading and copying solutions from other similar cases, but they are extremely specific to the user.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ren
  • 4,594
  • 9
  • 33
  • 61
  • It should just be `text[0]`, not `&text[0]`. – Barmar Oct 30 '15 at 21:59
  • 1
    --> `char text[7][100];`.. `i < 7 && fgets(text[i++],100,fp)`.. `printf("%s", text[0]);` – BLUEPIXY Oct 30 '15 at 22:00
  • 1
    The array should be `char text[7][100]`. You're declaring a 2-dimensional array of pointers, not an array of strings. – Barmar Oct 30 '15 at 22:00
  • Thanks to both, although a 2D array is my next goal for storing words individually in the array, I guess I was mixing things up. – Ren Oct 30 '15 at 22:02

2 Answers2

2

So part one, you don't need a pointer to a char[][]:

char text[7][100];

Part 2, just deference your array of strings like a normal person, nothing fancy here:

while(fgets((text)[i++],100,fp) != NULL) ;

Live example: http://ideone.com/MADAAs

Some things to watch out for:

  1. If your input file has more than 7 lines you are going to have problems.
  2. Why is “while ( !feof (file) )” always wrong?
Community
  • 1
  • 1
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • thanks, it solved it. the program I am trying to make and the file too are both very simple, so I am not worrying about those 2 last warnings, but thanks. – Ren Oct 30 '15 at 22:04
0
char * text[7][100]; //wrong - this is 2 diminutions array of char pointers, replace it with 
char text[7][100];

while(fgets((*text)[i++],100,fp) != NULL) ; // replace this with
 while(fgets(&text[i++][0],100,fp) != NULL) ; 

NOTE: this code will work in the current scope of the function (on the stack) if you need to use it outside the scope of current scope , allocate some memory on the heap and use the pointers of the heap.

Accountant م
  • 6,975
  • 3
  • 41
  • 61
  • @Ben why not right? ! I point to the first char in every string from the 7 strings of this array , `text[0][0]` `text[1][0]` `text[2][0]` `text[3][0]` `text[4][0]` `text[5][0]` `text[6][0]` – Accountant م Oct 30 '15 at 22:11