我正试着用C语言写下面的函数,
char* modelstrdup(char* source);
该函数应模仿标准C库函数strdup。该参数是我们希望复制的字符串。返回的指针将指向堆。在编写此函数时,请在保存string副本的堆上创建一个结构源。设置字符串的长度和容量等于源代码中的字符数。请确保将地址返回到字符串的第一个字符,而不是结构字符串的地址。
这是我的教授给我的唯一提示,但我甚至不知道从哪里开始...
//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);有什么建议吗?谢谢!
发布于 2009-10-26 07:17:06
给你个提示
char* strdup(char *str)
{
char* ret = (char*)malloc(strlen(str)+1);
//copy characters here
return ret;
}https://stackoverflow.com/questions/1622416
复制相似问题