c - "Expression must have class type" error for a defined class -


if define class this:

struct _hnum {    char *a; }; typedef struct _hnum hnum; 

and write function:

/* *allocates new hnum same value hnum. caller's * responsibility free returned hnum. * * return value: *   returns pointer new number, or null if allocation failed. */ hnum *hnum_clone(const hnum *hnum) {     hnum newnum;     if(!newnum.a)     {         return null;     }     strcpy(newnum.a, hnum.a); } 

the compiler gives "expression must have class type" error on "hnum" in line strcpy(newnum.a, hnum.a);. problem here?

this because hnum pointer. therefore, need dereference - either explicitly asterisk, or using -> operator instead of dot .:

strcpy(newnum.a, hnum->a); 

note: need add memory allocation , return statement, otherwise program has undefined behavior:

hnum *hnum_clone(const hnum *hnum) {     if(!hnum)     {         return null;     }     hnum *newnum = malloc(sizeof(hnum));     if (hnum->a) {         newnum->a = malloc(strlen(hnum->a)+1);         strcpy(newnum->a, hnum->a);     }     else     {         newnum->a = null;     }     return newnum; } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -