关于字符串指针的问题
用字符数组做参数 想用a覆盖b再输出希望能有人帮我看看哪里有问题在这里提前谢谢各位啦
#include<stdio.h>
void main(){
void copy_string(char *fron,char *to);
char *a = "i am a big fish";
char *b = "you are a small fish";
printf("String a = %s\nString b = %s \n",a,b);
printf("copy string a to string b: \n");
copy_string(a,b);
printf("\nString a = %s \nString b = %s \n",a,b);
}
void copy_string(char *fron,char *to){
for(;*fron!='\0';fron++,to++){
*to = *fron;
}
*to = '\0';
}
不知道你是从哪儿学来的 char *a = "i am a big fish";
char *b = "you are a small fish";
这种用法,你这是在向常量区的字符串添加一个非常量字符指针,然后试图修改常量区的值。检查严格的编译器会直接编译不通过
改成 char a[] = "i am a big fish";
char b[] = "you are a small fish";
Croper 发表于 2019-12-17 21:41
不知道你是从哪儿学来的
这种用法,你这是在向常量区的字符串添加一个非常量字符指针,然后试图修改常量区 ...
#include<stdio.h>
void main(){
void copy_string(char fron[],char to[]);
char a[] = "i love fishc";
char b[] = "you are a fish";
printf("string a = %s\nstring b = %s\n",a,b);
printf("copy string a to string b:\n");
copy_string(a,b);
printf("\nstring a = %s\nstring b = %s\n",a,b);
}
void copy_string(char fron[],char to[]){
int i =0;
while(fron !='\0'){
to = fron;
i++;
}
to = '\0';
}
答主说的应该是这种方法把,我这种错误可以在讲的详细一点吗 你只需要改我说的地方就行,其他都不用动#include<stdio.h>
void main(){
void copy_string(char *fron,char *to);
char a[] = "i am a big fish";
char b[] = "you are a small fish";
printf("String a = %s\nString b = %s \n",a,b);
printf("copy string a to string b: \n");
copy_string(a,b);
printf("\nString a = %s \nString b = %s \n",a,b);
}
void copy_string(char *fron,char *to){
for(;*fron!='\0';fron++,to++){
*to = *fron;
}
*to = '\0';
} char a[] = "i am a big fish"; //这是一个字符数组,长度为16,将其初始化赋值为i am a big fish
char *b="i am a big fish"; //字符指针b指向常量区字符串"i am big fish"其开头
char *c=”i am a big fish"; //常量区已经有字符串"i am big fish",字符指针c直接指向其开头,其值与b相同
页:
[1]