2013-04-30 101 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」?