课堂作业补充
#include<stdio.h> int main() { void funter(char *a,char *b); char *str1="hello world"; printf("%s\n",str1); char *str2="Hello World"; printf("%s\n",str2); funter(str1,str2); return 0; } void funter(char *a,char *b) { int i=0; printf("%s\n",a); printf("%s\n",b); printf("查看1\n"); for(;*b!='\0';a++,b++) {printf("查看2\n"); *a=*b;} printf("查看3\n"); printf("%s\n",a); for(i=0;i<11;i++) printf("%c",a[i]); }
hello world Hello World hello world Hello World 查看1 查看2 -------------------------------- Process exited after 2.622 seconds with return value 3221225477 请按任意键继续. . .
总结:
这是课堂上我的程序, 程序能编译但不能运行
程序运行到查看2,下面的 字符串赋值没有执行
这个程序我找不出错误,在修改的时候有出过
警告,意思是说我在定义字符数组的时候不能将
字符串赋值给指针,但我觉得不应该,因为 前
四个打印能打印出来,所以我觉得字符串赋值
给指针应该没错,现在我理解了,这个地方是字
符串赋给指针变量后不能再做任何改变,但我把程序
进行改造定义字符数组而不用指针指向字符数组
的首地址通过赋值语句和for循环将后一个字符数
组赋值给前一个。
#include<stdio.h> int main() { void funter(char *a,char *b); char str1[]="hello world"; printf("%s\n",str1); char str2[]="Hello World"; printf("%s\n",str2); funter(str1,str2); return 0; } void funter(char *a,char *b) { int i=0; printf("%s\n",a); printf("%s\n",b); printf("查看1\n"); for(i=0;i<11;i++) if(b[i]!='\0') a[i]=b[i]; else a[i]='\0'; printf("查看2\n"); printf("%s\n",a); for(i=0;i<11;i++) printf("%c",a[i]); }
hello world Hello World hello world Hello World 查看1 查看2 Hello World Hello World -------------------------------- Process exited after 0.2742 seconds with return value 0 请按任意键继续. . .
运行成功
按照老师要求:
#include<stdio.h> int main() { void funter(char a[]); char str[]="hello world"; printf("%s\n",str); str[0]='H'; str[6]='W'; printf("%s\n",str); funter(str); return 0; } void funter(char a[]) { int i; printf("%s\n",a); for(i=0;i<11;i++) printf("%c",a[i]); }
hello world Hello World Hello World Hello World -------------------------------- Process exited after 0.3231 seconds with return value 0 请按任意键继续. . .