Possible Duplicate:
Any better suggestions for this c functions copyString,concatString
这是一个求职面试的问题,我需要用特定的签名来实现它这是我需要工作的代码:
int main(int argc, char *argv[])
{
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7);
new_strcat(&str , " two");
new_printf(&str , "%str !", s);
puts(str );
new_free(&str);
return 0;
}
这是我对 new_strcpy 的实现:
char* new_strcpy(char **dst,const char *source)
{
char *ans=*dst;
while(**dst++=*source++);
return ans;
}
但是这个解决方案崩溃了,有人可以帮助我吗?
您的解决方案的问题是您未能为 *dst
分配内存。
考虑需要工作的前三行代码:
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7); // ***
由此可见:
new_strcpy()
需要为结果分配内存。
- 当重新分配
str
时,new_strcpy()
需要释放之前的 str
以避免内存泄漏。
- 要使上面的行
***
正常工作,释放必须发生在分配之后。
这是一个框架实现,可以为您提供思路。我根据 strcpy()
等实现函数,但如果调用库函数是不允许的,您可以编写自己的循环(您已经知道该怎么做)。
#include <stdlib.h>
#include <string.h>
void new_strcpy(char** dst, const char* src) {
char* orig_dst = *dst;
*dst = malloc(strlen(src) + 1);
strcpy(*dst, src); /* replace with a loop if calling strcpy() is not permissible */
free(orig_dst);
}
void new_strcat(char** dst, const char* src) {
char* orig_dst = *dst;
*dst = malloc(strlen(*dst) + strlen(src) + 1);
strcpy(*dst, orig_dst); /* replace with a loop if calling strcpy() is not permissible */
strcat(*dst, src); /* ditto for strcat() */
free(orig_dst);
}
void new_free(char** dst) {
free(*dst);
*dst = NULL;
}
int main(int argc, char *argv[])
{
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7);
new_strcat(&str , " two");
/* new_printf(&str , "%str !", s); */
puts(str );
new_free(&str);
return 0;
}
我将实现 new_printf()
作为读者的练习。 :-)