简体   繁体   中英

passing a pointer to a initialized structure in a function

I have this structure like following :

typedef struct{
char static_data[10];
int a;
int b;
} my_ds;

i have initialized it like following:

my_ds * ds = (my_ds *)malloc(sizeof(my_ds));
memmove(my_ds->static_data, buf, len);
ds->a = c;
ds->b = d;

and passed it in a function:

int my_fun(void ** data);
my_fun((void *)&ds);

what happens inside my_fun, the first field, static[10] is initialized correctly but other two values are zero. What am i missing here?

memmove()? I guess you intended to use memcpy() or strcpy() or maybe even strncpy() !

Also the double ** are (probably) not needed in my_fun(void **data) A void pointer can point to anything, including a void pointer. (but that depends on the function definition, which was not shown)

In that case, the ampersand (nor the cast) in my_fun ( (void**) &ds); is also not needed. any pointer can be cast into a void pointer in C.

my_ds * ds;
ds = malloc(sizeof *ds);
if (len >= sizeof my_ds->static_data) len = sizeof my_ds->static_data - 1;
memcpy(my_ds->static_data, buf, len);
my_ds->static_data[len] = 0;
ds->a = c;
ds->b = d;

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