文字列にスペースを割り当てる必要があります。Mallocは、必要なサイズのメモリスロットを返しますが、メモリの再割り当ては許可しません。そのためには、reallocがあります。
mallocを使用すると、テーブルのサイズが固定になります。これは、静的であると宣言しただけで、後で初期化した場合と同じです(mallocはそれよりもはるかに大きいため、この文に少し反対しますが、これについては目的それを言うのは安全です)。
Reallocはそれを行い、メモリを再割り当てしますが、iを正しく使用しないとかなり危険な場合があります。そして、私の意見では、それを行うための最も正しい方法ではありません。
サイズがわからないものを保存したい場合は、動的構造が最適です。'データ構造のような'リンクリストを使用できるので、必要な数の単語を使用して、そのリストを配列に変換できます。
私はこのようなもので行きます:
typedef struct _words{ //Structure to the dynamic insertion of words
char *word;
struct _words *next;
}words;
words *last; //Easier implementation for this case. Not always the best solution
words *init(){ //Is good practice to start with an empty structure for reference passing
words *new = malloc(sizeof(words));
if(new == NULL) exit(0);
new->next = NULL; //A good end/next reference
return new;
}
void insertWord(char *word){
words *new = malloc (sizeof(words));
if(new == NULL) exit(0);
new->word = malloc(strlen(word)*sizeof(char));
if(new->word == NULL) exit(0);
new->next = NULL; //Or new->next = last->next; wich is also null.
last->next = new;
last = new;
}
int main(){ //Or the name of your function
FILE *file = fopen ( filename, "r" );
words *list = init();
last = list;
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
int i = 0;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
insertWord(line);
i++;
}
//Here, you already have all the words in your dynamic structure. You can now save them into an array
char **array = malloc(i*sizeof(char*)); //i is the number of words.
if(array == NULL) exit(0);
word *aux = list->next;
if(aux != NULL){
for(int j=0;j<i && aux != NULL;j++){
array[j] = malloc(strlen(aux->word)*sizeof(char));
if(array[j] == NULL) exit(0);
strcpy(array[j], aux->word);
aux = aux->next; // jump to the next word
}
}
...
}
これはうまくいくかもしれないと思いますが、私はそれを試しませんでした。動的構造を実装する方法についてのアイデアを提供するだけです。
それはフリーを逃し、たとえ近くにあるとしても、実際のスタックではありません。
お役に立てれば。