Reputation: 3415
I am trying to write the following function in C,
char* modelstrdup(char* source);
The function should imitate the standard C library function strdup
. The parameter is the string that we wish to duplicate. The returned pointer will point onto the heap. When you write this function, create a structure string
on the heap that holds a copy of source. Set the length and capacity of your String equal to the number of characters in source. Be
sure to return the address to the first character in the string and not the address of the structure string.
This is the only hint my professor gave me, but I don't even know where to start...
//Client Program Format only, will not work!
char* s; // should be “yo!” when we‟re done
String* new_string = malloc(sizeof(String) + 10 + 1);
(*new_string).length = 3; // 3 characters in “yo!”
(*new_string).capacity = 10; // malloced 10 bytes
(*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? Thank you!
Upvotes: 0
Views: 1941
Reputation: 45124
Heres a hint
char* strdup(char *str)
{
char* ret = (char*)malloc(strlen(str)+1);
//copy characters here
return ret;
}
Upvotes: 4