2017-04-23 17 views
-2

我試圖實現自動完成功能的第一部分,該功能需要一個字符串,計算特定字母的索引,然後在該索引處分配另一個結構指針。它還在字符串數組中存儲可能的單詞完成。出於某種原因,當我嘗試訪問字符串數組字段時,程序崩潰了,我找不到原因。我怎樣才能解決這個問題?程序崩潰時訪問結構內的數組

感謝

struct table { 
    struct table *next[26]; 
    char **complete; 
    int lastIndex; 
    int size; 
}; 

static struct table Base={{NULL},NULL,0,0}; 

void insert(const char *string){ 
    int index=string[0]-'a'; 
    if(Base.next[index]==NULL){ 
     Base.next[index]=(struct table*)malloc(sizeof(struct table)); 
     *Base.next[index]=(struct table){{NULL},NULL,0,0}; 
    } 
    struct table *pointer=Base.next[index]; 
    if(pointer->lastIndex==pointer->size){  //expand complete array 
      pointer->complete[pointer->lastIndex] = strdup(string); //program crashes here 
      pointer->lastIndex=pointer->lastIndex+1;  
    } 
} 
+1

奇怪的行爲通常來自未定義的行爲,由錯誤的內存操作引起。如果您遇到**訪問違規**(分段錯誤),請嘗試使用[Valgrind](http://valgrind.org)或[AddressSanitizer](https://clang.llvm.org/docs/AddressSanitizer .html)來確定問題的根源。不要忘記定義術語「崩潰」。 –

+0

'pointer-> complete [pointer-> lastIndex]':'pointer-> complete'是'NULL'。它無法解除引用。 – BLUEPIXY

+0

當你分配結構時,你沒有分配table.complete。這是一個指向/ some指針的指針,所以pointer-> complete是undefined,就像pointer-> complete [n]一樣。 – Mike

回答

-1

你假設

const char * string 

將只包含小案字母。字典也有撇號 添加這種情況。

+0

錯誤的關於'static'(你的回答描述'const') –

2

在這一行

pointer->complete[pointer->lastIndex] = strdup(string); 

的崩潰是因爲pointer->completeNULL。換句話說,你忘記分配內存complete

我該如何解決這個問題?

您必須分配內存。看來你想要一個動態大小的char指針數組。因此,您需要使用realloc,以便您擴展分配的內存並保留以前的值。

喜歡的東西:

char** tmp = realloc(pointer->complete, (pointer->lastIndex + 1) * sizeof(char*)); 
if (tmp == NULL) 
{ 
    // Out of memory 
    exit(1); 
} 
pointer->complete = tmp; 

// Then you can do your normal code 
pointer->complete[pointer->lastIndex] = strdup(string); 

注意:雖然它可能每次都使用realloc你插入一個字符串,它可以完成相當糟糕。

因此,不要爲每個新字符串重新分配內存,每次調用realloc時重新分配一塊內存可能會更好。像:

if (pointer->lastIndex == pointer->size) 
{ 
    // Need more memory 
    // - if it's the first time just start with 10 (or another number) 
    // - else double the size 
    pointer->size = (pointer->size != 0) ? 2 * pointer->size : 10; 
    char** tmp = realloc(pointer->complete, (pointer->size) * sizeof(char*)); 
    if (tmp == NULL) 
    { 
     // Out of memory 
     exit(1); 
    } 
    pointer->complete = tmp; 
} 

在這裏,我決定做realloc時增加一倍分配的內存。您可以使用您喜歡的螞蟻方法,例如總是添加10個而不是加倍。

順便說一句:名稱lastIndex似乎很差,因爲它實際上是一個nextIndex變量。

上的數據結構的最後一句話

你的數據所有制結構即struct table似乎有點怪我。在基本級別上,您只能使用table。在下一個級別中,您不使用table,而只使用其他變量。

在我看來,你應該將結構分成兩個結構,如:

struct StringTable { 
    char **complete; 
    int lastIndex; 
    int size; 
}; 

struct table { 
    struct StringTable strings[26]; 
}; 

這將節省您的內存和一些動態內存分配。

+0

@ SD'Anc - 注意我原來的答案有一個愚蠢的錯誤。現在已經糾正了。 – 4386427

相關問題