如何传递一个指针结构到另一个函数在C中,在调用函数,如果我只能访问指针变量



我有一个函数

void get_alloc_single_struct(void **arr)
{
*arr=malloc(sizeof(**arr));
}
我想知道如何从main调用上面的函数,例如

我是这样做的

struct ads *data1=NULL;
get_alloc_single_struct(&(data1));

但是,但是我得到一个警告和"注意:…">

:29: warning: passing argument 1 of ‘get_alloc_single_struct’ from incompatible pointer type [-Wincompatible-pointer-types]
24 |     get_alloc_single_struct(&(data1));
|                             ^~~~~~~~
|                             |
|                             struct ads **
data.c:14:37: note: expected ‘void **’ but argument is of type ‘struct ads **’
14 | void get_alloc_single_struct(void **arr)

当使用-Wall -Wextra

编译时我做错了什么

使用("double void"例如,void **)在这里是一个危险信号。如果你想包装malloc(),最好的办法是保持相同的接口。

你不能同时让接口像这样使用void *让它使用sizeof计算所需的大小,因为当你使用void时,你显式地删除了类型信息。

所以,如果你想从调用中删除大小,你必须在函数本身中编码它,即专门化它:

struct ads * get_alloc_ads(void)
{
return malloc(sizeof (struct ads));
}

或者是100%换行并传入size:

void * get_alloc(size_t bytes)
{
return malloc(bytes);
}

当然,在后一种情况下,您还可以添加日志记录、故障退出或其他特定于应用程序的特性,否则包装将变得毫无意义。

函数get_alloc_single_struct有一个类型为void **的参数。必须为"struct ads **"。所以只要这样做:

void get_alloc_single_struct(void **arr) --> void get_alloc_single_struct(struct ads **arr)

原因是sizeof

如果有一个void **参数,你最终会得到sizeof(void),它是而不是你想要什么。如果需要sizeof(struct ads),则参数必须为struct ads **

说……这样写函数没有多大意义。当你只想知道对象类型的sizeof时,不需要传递指针给实际对象。

谢谢你的回答,我想我应该这样做

struct ads{
int id;
char *title;
char *name;
};
void* get_alloc_single(size_t bytes)
{
return malloc(bytes);
}
int main()
{
struct ads *data1=get_alloc_single(sizeof(struct ads));
data1->title=get_alloc_single(10);
strcpy(data1->title, "fawad khan")
data1->id=102;
printf("%s %dn",data1->title,data1->id);
return 0;
}

最新更新