I want to read a file and write each line to array of char. As I don’t know the amount of lines, therefore I thought the most efficient way is to use 2D array of char pointer. However I get segmentation fault.
My question might be duplicate of this one :
2D array of char pointers –> Segmentation fault?
But I couldn’t figure the correct syntax for C so I couldn’t try.
Here’s my code:
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
char **new_line;
int i = 0;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
strcpy(new_line[i], line);
i++;
}
Memory is not allocated for
new_linewhich causes the segmentation fault.If you know the no of lines, then you can declare that as local array itself. In that case your accessing method will works fine.
Your problem here is you dont know the maximum number of lines. So you have selected double pointer. In that case you need to first
mallocwith somennumber of lines and then you need to keep on usingreallocto increase the buffer size.Note : Take care of null check for
mallocandrealloc