>although you said it is broken I initialize the str every time I read a word from the file.
Hmm, I can interpret this one of two ways:
- You're saying the code you posted isn't equivalent to the code you're actually using.
- You're saying that I'm wrong and the code you posted isn't broken.
If it's the first case then I would highly recommend that you post equivalent examples to your real code if you want any useful help. If it's the second case then I pity you, because I'm very rarely wrong when it comes to the standard language/library, and when I am it's not the people asking beginner questions who are able to correct me successfully.
Arbitrary length input takes more work, and often the basic input functions are weak without a bit of scaffolding around them to get what you want. For example, here's a delimited string input function that can be used to read words:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GROW_BY 32 /* Arbitrary size */
char *reads ( FILE *in, char *delim )
{
char *result = NULL;
size_t size = 0;
size_t capacity = 0;
int ch;
while ( ( ch = getc ( in ) ) != EOF ) {
if ( size == capacity ) {
char *temp;
capacity += GROW_BY;
temp = realloc ( result, capacity + 1 );
if ( temp == NULL ) {
/*
This is a weak solution because it results in
loss of data. Recommend better error handling
*/
free ( result );
result = NULL;
break;
}
result = temp;
}
/* Order is important here; run *after* the resize step */
if ( strchr ( delim, ch ) != NULL )
break;
result[size++] = ch;
}
if ( result != NULL )
result[size] = '\0';
return result;
}
int main ( void )
{
char *s;
while ( ( s = reads ( stdin, " \n" ) ) != NULL ) {
printf ( ">%s<\n", s );
free ( s );
}
return 0;
}
Take careful note of how I handled the memory, this is a common pattern that you can reuse for an array of pointers to char. You can use this example to neatly fix your broken code
and find the answer to the original problem of creating a dynamic array. You're welcome.