简体   繁体   中英

how to pass a pointer to struct to another function in C, in calling function if I have access to only pointer variable

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

The use of types ("double void" ie 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, ie 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.

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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM