gpt4 book ai didi

c - 从 ‘void*’ 到 ‘char*’ 的转换无效错误

转载 作者:行者123 更新时间:2023-11-30 18:14:48 24 4
gpt4 key购买 nike

尝试查看过去处理此问题的问题,但所有这些似乎都与 C++ 而不是 C 相关。而且我必须用 C 编写程序。所以我有这部分代码,应该执行以下操作:修改strp 指向的现有 kstring 至少有 nbytes 字节长...等等。但是我有该函数的代码,但我不断收到错误:从“void*”到“char*”的转换无效。

typedef struct
{
char *data;
size_t length;
} kstring;

功能:

void kstrextend(kstring *strp, size_t nbytes)
{
char *nwData;
int lnth=strp->length;
if(lnth < nbytes)
{
// new array allocate with large size and copy data to new array
nwData = realloc(strp->data, nbytes);
// call abort in case of error
if(nwData == NULL)
{
abort();
}
//Making strp->data point to the new array
strp->data = nwData;
//Setting strp->length to the new size.
strp->length = nbytes;
// filled with '\0' in remaining space of new array
for (int lp = lnth; lp < nbytes; lp++)
{
strp->data[lp] = '\0';
}
}
}

调用函数的 main 部分:

name.data = (char*)calloc(sizeof("Hello"), 1);
strcpy(input, "Hello");
name.length=5;
kstrextend(&name,40);
printf("%s %d",name.data,name.length);

最佳答案

问题在于您调用 realloc 的位置:

// new array allocate with large size and copy data to new array
nwData = realloc(strp->data, nbytes);

nwData 是 char * 类型,但 realloc 返回 void *。请参阅https://en.cppreference.com/w/c/memory/realloc了解更多信息。您应该像设置 name.data 时那样转换为 char *:

nwData = (char *)realloc(strp->data, nbytes);

我假设您正在使用 g++ 进行编译?如果您正在编写 C 程序,则应该使用 gcc 进行编译,它将根据 C 语言语义而不是 C++ 进行编译。

顺便说一句,我发现您在循环中手动将数组的其余部分设置为 \0:

// filled with '\0' in remaining space of new array
for (int lp = lnth; lp < nbytes; lp++)
{
strp->data[lp] = '\0';
}

使用内置 memcpy 函数通常比使用循环要快得多(并且代码风格更好):

memset(strp->data + lnth, nbytes - lnth, '\0');

关于c - 从 ‘void*’ 到 ‘char*’ 的转换无效错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527688/

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