我在动态分配时遇到了问题。我的程序需要接收一个文本文件,取出每个单词,并将其放入一个数组中,同时对重复单词进行计数。我认为我正确地将单词放入数组中,但是我不明白如何用我使用动态分配创建的结构创建数组。即它需要像名单那样增长。感谢你给与我的帮助。我所评论的领域也是麻烦的领域。动态分配C
#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;
}
你是否得到任何构建错误?我有一种很好的感觉,你应该使用' - >'来取消引用'word'和'count'变量,因为你正在存储结构指针。 – 2013-04-30 01:35:58
' - >'表示法不正确,WORD_RECORD可能是一个指针,但他使用malloc()为十个结构分配存储空间,并且点符号是合适的。使用typedef没什么问题,你是什么意思“防止封装”? calloc()是分配存储的一种可行的替代方法,但我认为唯一的优点是它初始化了分配的存储空间,问题人员忘记了在问题代码中进行分配。 – 2013-04-30 01:41:44