我試圖實現自動完成功能的第一部分,該功能需要一個字符串,計算特定字母的索引,然後在該索引處分配另一個結構指針。它還在字符串數組中存儲可能的單詞完成。出於某種原因,當我嘗試訪問字符串數組字段時,程序崩潰了,我找不到原因。我怎樣才能解決這個問題?程序崩潰時訪問結構內的數組
感謝
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;
}
}
奇怪的行爲通常來自未定義的行爲,由錯誤的內存操作引起。如果您遇到**訪問違規**(分段錯誤),請嘗試使用[Valgrind](http://valgrind.org)或[AddressSanitizer](https://clang.llvm.org/docs/AddressSanitizer .html)來確定問題的根源。不要忘記定義術語「崩潰」。 –
'pointer-> complete [pointer-> lastIndex]':'pointer-> complete'是'NULL'。它無法解除引用。 – BLUEPIXY
當你分配結構時,你沒有分配table.complete。這是一個指向/ some指針的指針,所以pointer-> complete是undefined,就像pointer-> complete [n]一樣。 – Mike