请教,关于C语言指针的问题。
模仿string.h库中strcpy函数的实现,定义strcpt函数如下:
void strcpt(char *dst, char *src)
{
while(*dst++ = *src++);
}
主程序如下:
#include <stdio.h>
#include <string.h>
void strcpt(char *dst, char *src);
main()
{
char *result;
char *cptr;
cptr="who are you";
result=(char*)malloc(20 * sizeof (char));
strcpt(result,cptr);
printf("%s\n",result);
}
得到结果result字符串内容是who are you
但是,如果不调用函数strcpt直接编写主程序:
main()
{
char *result;
char *cptr;
cptr="who are you";
result=(char*)malloc(20 * sizeof (char));
while(*result++ = *cptr++);
printf("%s\n",result);
}
result得不到who are you 的预期结果,新手请教各位朋友这是为什么?
[解决办法]
while(*result++ = *cptr++);之后result已经指向字符串的末尾,这样printf当然打印不正确,你应该设置一个临时变量来保存之前的指针,例如:
char* p = result;
while(*p++ = *cptr++);
printf("%s\n",result);