从“ void *”到“ char *”的无效转换错误

时间:2019-02-05 04:31:55

标签: c

尝试查看过去处理此问题的问题,但所有这些问题似乎都与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';
        }
    }
}

调用函数的主要部分:

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

1 个答案:

答案 0 :(得分:-2)

问题在于您要调用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';
}

使用内置的memcpy函数比使用循环通常更快(更好的代码样式):

memset(strp->data + lnth, nbytes - lnth, '\0');
相关问题