字符串做函数参数
#include <stdio.h> #include <stdlib.h> #include <string.h> void copy_str21(char *from, char *to) { for(; *from != '\0'; from++, to++) { *to = *from; } *to = '\0'; } //* 操作和 ++操作 //++优先级高 void copy_str22(char *from, char *to) { for(; *from != '\0'; ) { *to++ = *from++; //先执行to++ from++ 再执行 *to++ = *from++ } *to = '\0'; } void copy_str23(char *from, char *to) { while((*to = *from) != '\0') { from++; to++; } } void copy_str24(char *from, char *to) { while((*to++ = *from++) != '\0') { ; } } void copy_str25(char *from, char *to) { while((*to++ = *from++)) { ; } } int main() { char *from = "abcde"; char buf2[100]; //copy_str21(from, buf2); //copy_str22(from, buf2); //copy_str23(from, buf2); //copy_str24(from, buf2); copy_str25(from, buf2); printf("buf2:%s\n", buf2); return 0; }
字符串拷贝的不同实现
字符串后的 ’\0‘
内存分配图
定义指针 一定要分配内存, 没有内存就没有指针
int copy_str26_good(char *from, char *to)
{
if(from == NULL || to == NULL)
{
return -1;
}
while ( *to++ = *from++) ; //空语句
}
执行语句之前先判断是否满足要求,如果满足再执行 while ( *to++ = *from++) ; 拷贝

以下代码对吗?
void copy_str25(char *from, char *to)
{
while((*to++ = *from++))
{
;
}
printf("from:%s \n", from);
}
指针的指向已经改变,已经调到‘\0’后面,故printf后面没有任何数据。
正确的代码应该重新定义辅助指针变量 把形参给接过来 不要轻易改变形参
void copy_str25(char *from, char *to)
{
char *tmpfrom = from;
char *tmpto = to;
if(from == NULL || to == NULL)
{
return -1;
}
while ( *to++ = *from++) ; //空语句
printf("from:%s \n", from); }
欢迎加入作者的小圈子
扫描下方左边二维码加入QQ交流群,扫描下方右边二维码关注个人微信公众号并,获取更多隐藏干货,QQ交流群:859800032 微信公众号:Crystal软件学堂
|
作者:Liu_Jing bilibili视频教程地址:https://space.bilibili.com/5782182 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在转载文章页面给出原文连接。 如果你觉得文章对你有所帮助,烦请点个推荐,你的支持是我更文的动力。 文中若有错误,请您务必指出,感谢给予我建议并让我提高的你。 |

浙公网安备 33010602011771号