NGix
NGix

Reputation: 2662

Dynamical array of strings in C

I'm trying to make array of strings, I have function rLine which reads line from stdin, each inputted line I need to save in array, but I don't have any idea about number of inputted string lines. So I need to dynamically increase array size to store them, I wrote such code:

char *res[2], *old = res;
while( 1 ){
  line = rLine( stdin ), len = strlen( line );
  res[row] = (char*)malloc( len + 1);
  strcpy( res[row++], line);
  res = (char**) realloc( res, row ); /* adding 1 more row, not sure adding size row? */
  if ( /*some cond*/ ) break;
}

But this code doesn't seem to work, how correctly declare array and increase it size?

Upvotes: 2

Views: 156

Answers (1)

imreal
imreal

Reputation: 10348

As I said in the comment, an array of pointers is different than a pointer to pointer. You can't try to assign allocated memory to an array.

You should declare res as a pointer to pointer and allocate memory at the beginning of the loop before using it.

Try it out like this:

char **res = NULL, *old = res;
while( 1 ){
  line = rLine( stdin ), len = strlen( line );
  res = (char**) realloc( res, sizeof(char**) * (row + 1) ); /* adding 1 more row, not sure adding size row? */
  res[row] = (char*)malloc( len + 1);
  strcpy( res[row++], line);
  if ( /*some cond*/ ) break;
}

Remember that arrays decay to pointers in most situations but are handled very differently underneath.

Upvotes: 3

Related Questions