char* utstrdup(char* source); -- This function is a mirror of the standard C lib
ID: 3610696 • Letter: C
Question
char* utstrdup(char* source);-- This function is a mirror of the standard C library functioncalled strdup.The parameter is a string that we wish to duplicate. The returnedpointer will point onto the heap. When you write this function,create a String struct on the heap that holds a copy of source. Setthe length and capacity of your String equal to the number ofcharacters in source. Be sure to return the address to the firstcharacter in your String (and not the address of the String structitself). any helpful hints on this will beawesome. we are also already given a malloc and anotherstruct in a different file and char* source is passedalreadytypedef struct String{ int length; int capacity; unsigned check; char ptr[0];
} String; thank you char* utstrdup(char* source);-- This function is a mirror of the standard C library functioncalled strdup.The parameter is a string that we wish to duplicate. The returnedpointer will point onto the heap. When you write this function,create a String struct on the heap that holds a copy of source. Setthe length and capacity of your String equal to the number ofcharacters in source. Be sure to return the address to the firstcharacter in your String (and not the address of the String structitself). any helpful hints on this will beawesome. we are also already given a malloc and anotherstruct in a different file and char* source is passedalready
typedef struct String{ int length; int capacity; unsigned check; char ptr[0];
} String; thank you thank you
Explanation / Answer
//Hope this will help you. #include #include #include typedef struct String { int length; int capacity; unsigned check; char *ptr; } String; char* utstrdup(char* source) { char *ptr= malloc(strlen(source)+1); String *my_s; my_s = malloc(sizeof(String)); strcpy(ptr,source); my_s->capacity = my_s->length = strlen(source); my_s->ptr =ptr; return ptr; } int main(){ char *s="test string"; char *ptr; ptr = utstrdup(s); printf("ptr is %s",ptr); system("pause"); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.