Eijomjo
Eijomjo

Reputation: 102

Dynamically allocated array with dynamically allocated string elements, using getline()

I'm trying to create a dynamically allocated array with dynamically allocated string elements, using getline().

This is my code,

char** getWordlist()
{
    FILE* fp = fopen( "Wordlist", "r" );
    if( errno == ENOENT )                   
        fp = fopen( "Wordlist", "w+r" );
    if( !fp ) {
        perror( "Could not open wordlist" );
    exit(EXIT_FAILURE);
}

int c, fileLines = 0;
do{
    c = fgetc(fp);
    if( c == '\n')
        fileLines++;
} while( c != EOF );
rewind(fp);


char** wordlist = calloc( fileLines, sizeof(char*) );  
for( c = 0; c < fileLines; c++ )
    getline( &wordlist[c], 0, fp );

     printf( "%s", (wordlist[0]) );

fclose(fp);
return wordlist;    
} 

However, printf prints outputs (null), so the strings was never created I think.

What am i doing wrong?

Upvotes: 1

Views: 147

Answers (2)

user3629249
user3629249

Reputation: 16540

regarding this line:

printf( "%s", (wordlist[3]) );

It is trying to print the wrong line. and it is not part of the for() loop that is reading the lines from the file.

Suggest:

size_t lineLength = 0;
for( int i = 0; i < fileLines; i++ )
{
     getline( &(wordlist[i]), &lineLength, fp );
     printf( "%s\n", wordlist[i] );
}

Upvotes: 0

chux
chux

Reputation: 154305

Incorrect usage of getline()

Pass address of size_t rather than 0.

for( c = 0; c < fileLines; c++ )
  // getline( &wordlist[c], 0, fp );
  size_t size = 0;
  getline( &wordlist[c], &size, fp );

To fix a potential off by 1 in line count calculation

int c;
size_t fileLines = 0;
int previous = '\n';
while ((c = fgetc(fp)) != EOF) {
    if( previous == '\n') fileLines++;
    previous = c;
}

Upvotes: 3

Related Questions