在C中创建strdup

时间:2009-10-25 23:09:41

标签: c

我正在尝试在C中编写以下函数,

char* modelstrdup(char* source);

该函数应模仿标准C库函数strdup。参数是我们希望复制的字符串。返回的指针将指向堆。编写此函数时,在堆上创建一个包含源副本的结构string。设置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);

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:4)

这是一个提示

char* strdup(char *str)
{
        char* ret = (char*)malloc(strlen(str)+1);

        //copy characters here
        return ret;
}