![](/img/trans.png)
[英]how to pass struct pointer as argument in a variable argument function in C
[英]how to pass a pointer to struct to another function in C, in calling function if I have access to only pointer variable
我有一个功能
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% 包裹并传入尺寸:
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 %d\n",data1->title,data1->id);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.