试图寻找解决这一问题,但所有这些问题过去似乎涉及到C ++不是C.我必须用C编写的程序,所以我有一个假设做以下的这部分程序:修改现有kstring ,指向STRP,必须至少为nbytes字节长......等等。但我对函数的代码,但我不断收到一个错误:从“无效*”到“字符*”无效的转换。
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';
}
}
}
的主要部分,其中函数被调用:
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以获取更多信息。而应该投给你设置char *
时做name.data
:
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';
}
它通常是更快(和更好的代码风格),使用内置的qazxsw POI功能,而不是使用一个循环:
memcpy