为什么重新定义一个指针r,指向p1+m-1就能够运行,但是这样就不行
#include <stdio.h>
#include <string.h>
int main()
{void copystr(char *,char *,int);
int m;
char str1[20],str2[20];
printf("input string:");
gets(str1);
printf("which character that begin to copy?");
scanf("%d",&m);
if (strlen(str1)<m)
printf("input error!");
else
{copystr(str1,str2,m);
printf("result:%s\n",str2);
}
return 0;
}
void copystr(char *p1,char *p2,int m)
{
char * r;
r = p1+m-1;
while (*r !='\0')
{*p2=*r;
r++;
p2++;
}
*p2='\0';
}```c
您好 (p1+m-1)是一个值,也就是左值,它是不允许被赋值的,你想要做的应该是p1的地址自增。
具体实现代码参考如下:
void cpstr(char *p1,char *p2,int m)
{
while(*(p1) != '\0')
{
*p2 = *(p1);
p1++;
p2++;
}
}
int main(void)
{
char *a = "aaaaa";
char b[10];
printf("%s\n%s\n",a,b);
cpstr(a,b,4);
printf("%s\n%s\n",a,b);
return 0;
}
你参数列表第二个传进来是干啥用的,有点费解。
实参里的第二个参数有没有初始化地址,会不会出现野指针的情况