使用 void 指针导致编译器警告错误
Use of void pointer causes compiler warning errors
我正在尝试创建一个分配内存并检查内存分配是否已完成的函数。为了允许分配任何内存类型,我将函数设置为接受 void,如下所示:foo(void ***memory, size_t pointer_type)
。这里的目的是让用户在第一段中输入任意指针,然后在第二段中输入指针类型的大小来正确分配,例如:
int foo(void ***memory,size_t pointer_type)
{
void **temp;
if((temp=calloc(10,pointer_type))==NULL)
{
return(-1);
}
for(i=0;i<10;i++)
{
if((temp[i]=calloc(10,pointer_type))==NULL)
{
// free array as can't be used
for(i;i>=0;i--)
{
free(temp[i]);
temp[i]=NULL;
}
free(temp);
temp=NULL;
return(-1);
}
}
*memory=temp;
return(0);
}
int main()
{
double **pointer;
if(foo(&pointer, sizeof(double))==-1)
{
return(-1);
}
//do stuff then free memory
return (0);
}
在此示例中,应创建双精度数组。我在阅读其他 SE 帖子时想到了这个想法,解释说这允许创建任何数组类型,但是编译器给出以下警告:
warning: passing argument 1 of 'foo' from incompatible pointer type
note: expected void ***'
but argument is of type 'double ***'
这向我表明我所做的事情是不正确的,但是在分配后将数组视为双数组时一切正常,所以我不知道该怎么做。
编辑:好的,所以 3 星的使用是从一个单独的函数为二维数组分配内存,这就是我被展示的方式,即如果我使用 pointer[a][b]=10
那么它会像一个二维数组。如果有更好的方法那么请展示一个例子,但是我仍然要求数组是当前紧迫的任何类型。
编译器产生正确的警告,因为类型
void ***
不同于类型
double ***
显式转换将修复警告:
if (foo((void ***)&pointer, sizeof(double))==-1)
只有一个void*
被认为是一个void
-指针,与其他指针的相互转换隐式完成(在 C 中)。
void**
是指向 void
指针的指针,它不是 void
指针。同样适用于 void***
.
因此,要修复您引用的错误,请更改
int foo(void ***memory,size_t pointer_type)
成为
int foo(void *memory, size_t pointer_type)
我正在尝试创建一个分配内存并检查内存分配是否已完成的函数。为了允许分配任何内存类型,我将函数设置为接受 void,如下所示:foo(void ***memory, size_t pointer_type)
。这里的目的是让用户在第一段中输入任意指针,然后在第二段中输入指针类型的大小来正确分配,例如:
int foo(void ***memory,size_t pointer_type)
{
void **temp;
if((temp=calloc(10,pointer_type))==NULL)
{
return(-1);
}
for(i=0;i<10;i++)
{
if((temp[i]=calloc(10,pointer_type))==NULL)
{
// free array as can't be used
for(i;i>=0;i--)
{
free(temp[i]);
temp[i]=NULL;
}
free(temp);
temp=NULL;
return(-1);
}
}
*memory=temp;
return(0);
}
int main()
{
double **pointer;
if(foo(&pointer, sizeof(double))==-1)
{
return(-1);
}
//do stuff then free memory
return (0);
}
在此示例中,应创建双精度数组。我在阅读其他 SE 帖子时想到了这个想法,解释说这允许创建任何数组类型,但是编译器给出以下警告:
warning: passing argument 1 of 'foo' from incompatible pointer type note: expected
void ***'
but argument is of type'double ***'
这向我表明我所做的事情是不正确的,但是在分配后将数组视为双数组时一切正常,所以我不知道该怎么做。
编辑:好的,所以 3 星的使用是从一个单独的函数为二维数组分配内存,这就是我被展示的方式,即如果我使用 pointer[a][b]=10
那么它会像一个二维数组。如果有更好的方法那么请展示一个例子,但是我仍然要求数组是当前紧迫的任何类型。
编译器产生正确的警告,因为类型
void ***
不同于类型
double ***
显式转换将修复警告:
if (foo((void ***)&pointer, sizeof(double))==-1)
只有一个void*
被认为是一个void
-指针,与其他指针的相互转换隐式完成(在 C 中)。
void**
是指向 void
指针的指针,它不是 void
指针。同样适用于 void***
.
因此,要修复您引用的错误,请更改
int foo(void ***memory,size_t pointer_type)
成为
int foo(void *memory, size_t pointer_type)