use*_*007 3 c string strcpy strcat
这是一个面试的问题,我需要用特定的签名来实现它,这是我需要工作的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我对new_strcpy的实现:
char* new_strcpy(char **dst,const char *source)
{
char *ans=*dst;
while(**dst++=*source++);
return ans;
}
Run Code Online (Sandbox Code Playgroud)
但这个解决方案崩溃了,有人可以帮帮我吗?
您的解决方案的问题是您无法为其分配内存*dst.
考虑需要工作的代码的前三行:
char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7); // ***
Run Code Online (Sandbox Code Playgroud)
由此可见,很明显:
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;
}
Run Code Online (Sandbox Code Playgroud)
我把实施new_printf()作为练习给读者.:-)