lvalue require as increment operand
1 #include<stdio.h> 2 #include<stdlib.h> 3 int main() 4 { 5 char source[]="hello"; //创建一个字符串数组值为“hello” 6 char* des =(char*)malloc(5*sizeof(char)); //初始化一个长度为5的空的字符串数组 7 8 for(int i=0;i<5;i++) //通过for循环将source中的元素拷贝到des中 9 { 10 *des++=*source++; 11 } 12 13 printf("%s",des); 14 return 0; 15 }
结果:
编译器报错:lvalue require as increment operand (错误在第10行)
自己的理解:
原来 在这里如果要使用 *des++ 或者 *source++ 那么 des 或 source 就需要是个能进行加一操作的指针也就是地址,然而在上面的代码中
des 和 source 并不是个地址 而是两个字符串数组;
那么按照这个想法,改变一下,先定义两个 指针 char* c 和 char* k 分别指向两个字符串数组的首地址,然后再对 这两个指针进行增加加操作
1 #include<stdio.h> 2 #include<stdlib.h> 3 int main() 4 { 5 char source[]="hello"; 6 char* des =(char*)malloc(5*sizeof(char)); 7 8 char* c = des; 9 char* k = source; 10 for(int i=0;i<5;i++) 11 { 12 *c++=*k++; 13 } 14 printf("%s",des); 15 return 0; 16 }
结果:
编译成功无报错,并得到了预期的结果
补充:
字符串拷贝的典型实现:
1 char *strcpy(char *des, char * source) //des 为目标字符串数组,source为源数组 2 { 3 char* r = des; 4 /* 5 assert 来自于c标准库<assert.h>,表示如果括号中的表达式为false则终止程序执行 6 为true不做任何操作 7 */ 8 assert((des != NULL)&&(source != NULL)); 9 while((*r++ = *source++)!='\0'); 10 return des; 11 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步