char *b和char a[]

来源:互联网 发布:mac 配置搜狗输入法 编辑:程序博客网 时间:2024/06/06 17:02

学生很勤奋,这学期新开的C语言已经自学到指针了。今天发了段代码过来,不知道错在哪里?看了一会,发现这个问题很多学生都会犯,甚至老师也不会注意。所以,整理下,以备查。

学生代码如下:

#include "stdio.h"
void copy_string(char *from, char *to)
{

for (; *from != '\0';* from++,*to++)
{
*to = *from;
}
*to= '\0';
}


int main()
{
char *a = "I am a student";
char *b = "YOU are a student";
printf("string a is :%s\n", a);
printf("string b is :%s\n", b);
printf("copy string a to b\n");
copy_string(a, b);
printf("string a is :%s\n", a);
printf("string b is :%s\n", b);
return 0;
}

简单的字符串复制,运行时错误。将char *b="You are a student"改为char b[]="you are a student",程序运行正常。原因就在于char *b="you are a student",b是一个指针,这个指针可以被修改,它可以指向新的地址。现在它指向的是字符串常量“you are a student”,字符串常量存储在constant section(常量区)里,不可被修改。char b[]="you are a student".b是数组名,其实质是指针常量,指向的位置是数组第一个元素所在的位置,b不能被修改。然而它的空间是在栈里面分配的,当前存储的是字符串"you are a student",它的内容是可以被重新修改赋值的。

3 0
原创粉丝点击