gpt4 book ai didi

c - 二维字符数组动态重新分配失败

转载 作者:行者123 更新时间:2023-11-30 17:40:47 25 4
gpt4 key购买 nike

这是代码片段。字典格式为:{word word\n word word\n...}

程序在第二次重新分配二维数组 roWords 时似乎失败了,我不知道为什么。

声明中:char ** roWords = NULL, **enWords == NULL;

while (fgets(buffer, 100, dictionary))
{
counter++;

roWords = (char**)realloc(roWords, sizeof(char*)* counter );
enWords = (char**)realloc(enWords, sizeof(char*)* counter );

p = strtok(buffer, " \n");


roWords[counter - 1] = NULL;
roWords[counter - 1] = (char*)realloc(roWords, sizeof(char)* strlen(p));
strcpy(roWords[counter - 1], p);


p = strtok(NULL, " \n");


enWords[counter - 1] = NULL;
enWords[counter - 1] = (char*)realloc(enWords, sizeof(char)* strlen(p));
strcpy(enWords[counter - 1], p);


}

最佳答案

解决方案是:

while (fgets(buffer, 100, dictionary))
{
counter++;

if (counter == 1)
{
roWords = (char**)malloc(sizeof(char*));
enWords = (char**)malloc(sizeof(char*));
}
else
{
roWords = (char**)realloc(roWords, sizeof(char*)* counter);
enWords = (char**)realloc(enWords, sizeof(char*)* counter);
}

p = strtok(buffer, " \n");


roWords[counter - 1] = (char*)malloc(sizeof(char) * (strlen(p) + 1));
strcpy(roWords[counter - 1], p);
roWords[counter - 1][strlen(p)] = '\0';

p = strtok(NULL, " \n");


enWords[counter - 1] = (char*)malloc(sizeof(char)* (strlen(p) + 1));
strcpy(enWords[counter - 1], p);
enWords[counter - 1][strlen(p)] = '\0';

}

关于c - 二维字符数组动态重新分配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21363274/

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