malloc - C Dynamic Memory Allocation to void pointer -
malloc - C Dynamic Memory Allocation to void pointer -
i have function pass struct id , homecoming me string. pass pointer store name string , pointer allocated memory function called.
int convertidtoname(void *id, void *name, size_t *size) { int status = 0; unsigned char *xidname = "user4.microsoft.com"; *name = (unsigned char*)malloc(30); memcpy(*name, xidname, *size); ... return(0); } main(int argc, char* argv[]) { struct id_t idobj ={1,5, {0,0,0,0,0,5}}; unsigned char* idname = null; uint32 idnamesize = max_char; convertidtoname(&idobj, &idname, (size_t *)&idnamesize); return(0); } the function convertidtoname() fails store allocated memory address in void pointer. unable assign memory in pointer , gives me error 3rd statement of function convertidtoname():
warning: dereferencing âvoid *â pointer test_code.c:683: error: invalid utilize of void look what doing wrong , how right it?
the name parameter of type void *, , you're dereferencing using *name. need utilize pointer of type unsigned char ** within function or cast name unsigned char ** before dereferencing it:
/* utilize namep instead of name. */ unsigned char **namep = name; *namep = malloc(30); memcpy(*namep, xidname, *size); ... or:
/* utilize casts everywhere. */ *(unsigned char **)name = malloc(30); memcpy(*(unsigned char **)name, xidname, *size); ... edit
as suggested @whozcraig, may create function require name void ** instead of void *. avoid need type casting or variable. great suggestion since malloc returns void * , memcpy requires void * parameter. dereferencing void ** yield void * work with.
c malloc
Comments
Post a Comment