我在动态分配时遇到问题。我的程序需要接收一个文本文件,接收每个单词,并将它们放入一个数组中,同时计算重复的单词。我认为我将单词正确地分配到数组中,但是我不明白如何使用我使用动态分配创建的结构创建数组。即它需要像列表一样增长。感谢你给与我的帮助。我注释掉的领域也是麻烦的领域。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned int uint;
typedef struct wordType
{
char * word;
uint count;
};
/* store the string in another temp string which you can iterate through
and compare with the array of non-repeated words. if there, increment*/
int main( void )
{
typedef struct wordType * WORD_RECORD;
WORD_RECORD arrayOfWords = malloc(10 * sizeof( WORD_RECORD) );
FILE * inputFile;
char temp[50];
uint i;
uint j;
uint size;
uint exists;
inputFile = fopen( "input.txt", "r");
if( inputFile == NULL )
{
printf( "Error: File could not be opened" );
/*report failure*/
return 1;
}
i = 0;
size = 0;
while( fscanf( inputFile, "%s", temp) == 1 )
{
exists = 0;
for( j = 0; j < size; j++ )
{
if( strcmp( arrayOfWords[j].word, temp ) == 0 )
{
arrayOfWords[j].count++;
exists = 1;
}
}
if( exists == 0 )
{
arrayOfWords[i].word = malloc(sizeof(char)
* (strlen(temp)+1));
strcpy( arrayOfWords[i].word, temp );
/*arrayOfWords[i].count++;*/
size++;
}
i++;
}
for( i = 0; i < (size-1) ; i++ )
printf("%s\n", arrayOfWords[i].word);
fclose( inputFile );
/*for( i = 0; i < size-1; i++ )
free( arrayOfWords[0].word );*/
return 0;
}