2013-04-30 103 views
0

我在动态分配时遇到了问题。我的程序需要接收一个文本文件,取出每个单词,并将其放入一个数组中,同时对重复单词进行计数。我认为我正确地将单词放入数组中,但是我不明白如何用我使用动态分配创建的结构创建数组。即它需要像名单那样增长。感谢你给与我的帮助。我所评论的领域也是麻烦的领域。动态分配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; 
} 
+0

你是否得到任何构建错误?我有一种很好的感觉,你应该使用' - >'来取消引用'word'和'count'变量,因为你正在存储结构指针。 – 2013-04-30 01:35:58

+1

' - >'表示法不正确,WORD_RECORD可能是一个指针,但他使用malloc()为十个结构分配存储空间,并且点符号是合适的。使用typedef没什么问题,你是什么意思“防止封装”? calloc()是分配存储的一种可行的替代方法,但我认为唯一的优点是它初始化了分配的存储空间,问题人员忘记了在问题代码中进行分配。 – 2013-04-30 01:41:44

回答

2

您似乎正确使用malloc()来初始化arrayOfWords数组。您可以使用realloc()函数来增长阵列,但是您必须记录它有多大,以便您知道何时拨打realloc()。在if (exists == 0)的情况下,变量arrayOfWords[i].count尚未初始化,所以假设它为零是一个错误,试图增加它是一个错误,除了将其设置为显式值(在本例中为0) ,是一个错误。

你似乎是使用i来计算单词总数你读过,不独特话你读过,所以使用i作为循环计数器,当你打印出来的话是错误的为好。这同样适用于当你释放malloc()的编辑词语时:使用i作为循环计数器意味着你最终得到了从malloc()未得到的free()

动态增长的存储你的单词列表,你需要保持多少struct wordType项目的跟踪已分配的存储空间,并增加了一个新词时,请检查您是否已经达到限额,如有必要,请拨打realloc()

当循环打印(和释放)这些单词时,为什么要做“size-1”?