Reputation: 4364
I have a function
void get_alloc_single_struct(void **arr)
{
*arr=malloc(sizeof(**arr));
}
I like to know how to call this above function from main for example
I am doing it like this
struct ads *data1=NULL;
get_alloc_single_struct(&(data1));
But But I am getting a warning and "note:..."
: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)
when compiled with -Wall -Wextra
What I am doing wrong
Upvotes: 0
Views: 66
Reputation: 4364
thanks for the answers I think I should do it like this
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;
}
Upvotes: -1
Reputation: 44330
The function get_alloc_single_struct
shall not have a parameter of type void **
. The parameter must be struct ads **
. So simply do:
void get_alloc_single_struct(void **arr) --> void get_alloc_single_struct(struct ads **arr)
The reason is sizeof
...
With a void **
parameter, you end up doing sizeof(void)
which is not what you want. You want sizeof(struct ads)
so the parameter must be struct ads **
.
That said... It doesn't make much sense to write the function like that. Passing a pointer to an actual object is not needed when all you want is to know the sizeof of an object type.
Upvotes: 1
Reputation: 399889
The use of types ("double void" i.e. void **
) is a bit of a red flag here. If you want to wrap malloc()
, the best idea is to keep the same interface.
You cannot both make the interface use void *
like that, and have it compute the required size using sizeof
, since you explicitly drop the type information when you go void
.
So, if you want to drop the size from the call you have to encode it in the function itself, i.e. specialize it:
struct ads * get_alloc_ads(void)
{
return malloc(sizeof (struct ads));
}
or be a 100% wrap and pass in the size:
void * get_alloc(size_t bytes)
{
return malloc(bytes);
}
of course in the latter case you could also add logging, exit-on-failure, or other features specific to your application otherwise the wrapping becomes pointless.
Upvotes: 1