用c语言解决问题3.下面程序是用指针法将一个字符串a复制到字符串b中,修改程序实现问题(1)(2)。void main(){char a[]="I am a boy.",b[20], *p1,*p2;int i;p1=a;p2=b;for( ; *p1!=’\0’;p1++,p2++)*p2=*p1;*p2=’\0’;printf("string a is:%s\n",a);printf("string b is:");for(i=0;b[i]!=’\0’;i++)printf("%c",b[i]);}(1)将第一个for循环改为while循环;(2)分别用指针变量p1和p2输出字符串a 和b。
时间: 2023-11-28 09:50:19 浏览: 44
(1) 将第一个 for 循环改为 while 循环:
```c
void main(){
char a[]="I am a boy.", b[20], *p1, *p2;
int i;
p1 = a;
p2 = b;
while (*p1 != '\0') {
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
printf("string a is: %s\n", a);
printf("string b is: ");
for (i = 0; b[i] != '\0'; i++) {
printf("%c", b[i]);
}
printf("\n");
}
```
(2) 分别用指针变量 p1 和 p2 输出字符串 a 和 b:
```c
void main(){
char a[]="I am a boy.", *p1, *p2;
int i;
p1 = a;
p2 = (char*)malloc(strlen(a) + 1); // 动态分配内存
while (*p1 != '\0') {
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
p1 = a;
p2 = p2 - strlen(a); // 指针后移
printf("string a is: ");
while (*p1 != '\0') {
printf("%c", *p1);
p1++;
}
printf("\n");
printf("string b is: ");
while (*p2 != '\0') {
printf("%c", *p2);
p2++;
}
printf("\n");
free(p2 - strlen(a)); // 释放内存
}
```
阅读全文