char *b和char a[]

学生很勤奋,这学期新开的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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值