gpt4 book ai didi

c - 结构指针数组段错误

转载 作者:行者123 更新时间:2023-11-30 17:01:43 27 4
gpt4 key购买 nike

我正在构建一个自动完成程序,它接受一些输入字符并返回建议的单词来完成这些字符。我有一个 AutoComplete_AddWord 函数,可以添加建议词。但是,每当我尝试访问结构补全数组(为给定主机表的字母最多保留 10 个建议单词)时,就会引发段错误。不知道我哪里错了。感谢您的帮助。

struct table {
struct table *nextLevel[26];
char *completions[10]; /* 10 word completions */
int lastIndex;
};

static struct table Root = { {NULL}, {NULL}, 0 }; //global representing the root table containing all subsequent tables

void AutoComplete_AddWord(const char *word){
int i; //iterator
char *w = (char*)malloc(100*(sizeof(char));
for(i = 0; w[i]; i++){ // make lowercase version of word
w[i] = tolower(word[i]);
}

char a = 'a';

if(w[0] < 97 || w[0] > 122)
w++;
int index = w[0] - a; // assume word is all lower case
if(Root.nextLevel[index] == NULL){
Root.nextLevel[index] = (struct table*) malloc(sizeof(struct table));
TotalMemory += sizeof(table);
*Root.nextLevel[index] = (struct table){{NULL},{NULL},0};
}
else
// otherwise, table is already allocated

struct table *pointer = Root.nextLevel[index];

pointer->completions[0] = strdup(word); //Here is where seg fault keeps happening
}

最佳答案

好的,所以这个有很多错误,而且你显然没有测试它并编译它。但我很好奇,所以仔细一看,问题就出在这里:

for(i = 0; w[i]; i++){ // make lowercase version of word
w[i] = tolower(word[i]);
}

您正在进入一个循环检查 w[0],一个新的、未初始化的内存块。

将其更改为:

for(i = 0; word[i]; i++){ // make lowercase version of word
w[i] = tolower(word[i]);
}

将解决这个问题。修复上面提到的其他杂项问题,代码的非段错误版本如下所示:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

struct table {
struct table *nextLevel[26];
char *completions[10]; /* 10 word completions */
int lastIndex;
};

int TotalMemory = 0;

static struct table Root = { {NULL}, {NULL}, 0 }; //global representing the root table containing all subsequent tables

void AutoComplete_AddWord(const char *word){
int i; //iterator
char *w = (char*)malloc(100*(sizeof(char)));

for(i = 0; word[i]; i++){ // make lowercase version of word
w[i] = tolower(word[i]);
}

char a = 'a';


if(w[0] < 97 || w[0] > 122) w++;
int index = w[0] - a; // assume word is all lower case

if(Root.nextLevel[index] == NULL){
Root.nextLevel[index] = (struct table*) malloc(sizeof(struct table));
TotalMemory += sizeof(struct table);
*Root.nextLevel[index] = (struct table){{NULL},{NULL},0};
}

struct table *pointer = Root.nextLevel[index];

pointer->completions[0] = strdup(word); //Here is where seg fault keeps happening
}

int main(int argc, char **argv)
{
AutoComplete_AddWord("testing");
return 0;
}

我无法说出该程序接下来会发生什么,但至少这可以让您克服段错误。

关于c - 结构指针数组段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878664/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com