Featured post
c - Using pointers and structs -
hello i'm not sure if i'm understand following piece of code. glad if read explanations , correct me if i'm wrong.
first of i'm declaring struct 3 arrays of char , integer.
struct employee { char last[16]; char first[11]; char title[16]; int salary; };
after declare function takes 3 pointers char , integer value. function uses malloc() , sizeof() create struct on heap. creations of object on heap not clear me. when use struct employee* p = malloc(sizeof(struct employee))
, happens there exactly?
happens when use function struct employee* createemployee (char* last, char* first, char* title, int salary)
several times different input. know pointer p isn't same pointer same struct on heap. rewrite information on heap, when use function several times? or create new object in different memory space?
struct employee* createemployee(char*, char*, char*, int); struct employee* createemployee(char* last, char* first, char* title, int salary) { struct employee* p = malloc(sizeof(struct employee)); if (p != null) { strcpy(p->last, last); strcpy(p->first, first); strcpy(p->title, title); p->salary = salary; } return p; }
i glad if explain me. thank much.
the malloc
function allocates new bytes on heap , returns pointer.
so createemployee
function allocates new memory every time it's called, fills data (in unsafe way - consider using strncpy
instead) , returns pointer memory. return different pointer every time it's called.
each instance create function exist long don't call free
on pointer.
- Get link
- X
- Other Apps
Comments
Post a Comment