我遇到动态分配问题。我的程序需要接收一个文本文件,接收每个单词,并将它们放入一个数组中,同时计算重复的单词。我认为我正在将这些单词正确地存储到数组中,但是我不明白如何使用动态分配创建的结构来创建数组。即它需要像列表一样增长。感谢你给与我的帮助。我所评论的领域也是有问题的。
#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;
}
答案 0 :(得分:2)
您似乎正确使用malloc()
来初始化您的arrayOfWords数组。你可以使用realloc()
函数增长数组,但是你必须跟踪你有多少单词的大小,这样你才能知道何时调用realloc()
。在if ( exists == 0 )
的情况下,变量arrayOfWords[i].count
尚未初始化,因此假设它为零是一个错误,尝试递增它是一个错误,除了将其设置为显式之外的任何其他内容值(在这种情况下,0
),是一个错误。
您似乎正在使用i
来计算您已阅读的字词总数,而不是您已阅读的唯一字词,因此使用i
作为循环打印出来的单词也是错误的。当您释放malloc()
'ed字时也是如此:使用i
作为循环计数器意味着您最终free()
从malloc()
获得的内容}。
要动态增加单词列表的存储空间,您需要跟踪已为其分配存储空间的struct wordType
个项目,并在添加新单词时检查是否已达到你的限制,如果有必要的话realloc()
。
当循环打印(并释放)单词时,你为什么要做“size-1”?