I am trying to write the following function in C,
char* modelstrdup(char* source);
The function should mimic the standard C library function strdup. The parameter is the string we want to duplicate. The returned pointer will point to the heap. When you write this function, create a structure stringon the heap that contains a copy of the source. Set the length and capacity of your string to the number of characters in the source. Be sure to return the address of the first character in the string, and not the address of the string string.
This is the only hint my professor gave me, but I don’t even know where to start ...
char* s;
String* new_string = malloc(sizeof(String) + 10 + 1);
(*new_string).length = 3;
(*new_string).capacity = 10;
(*new_string).signature = ~0xdeadbeef;
(*new_string).ptr[0] = „y‟;
(*new_string).ptr[1] = „o‟;
(*new_string).ptr[2] = „!‟;
(*new_string).ptr[3] = 0;
s = (*new_string).ptr;
printf("the string is %s\n", s);
Any suggestions? Thanks!
source
share