为了账号安全,请及时绑定邮箱和手机立即绑定

C语言 C字符串指针

C语言 C字符串指针

C
第四首歌 2015-10-25 23:29:23
当把char* to ="You are a student."换成:char a[]="You are a student.";char *to=a;没问题。编译,连接没问题,但运行就出问题了。调试显示:"unhandled exception  in Test01025.exe:0xC000005:Access Violation."请问这是什么原因?#include<stdio.h>int main(){ void copy_string(char *from,char *to); char *from="I am a teacher."; char *to="You are a student.";//当把这一行换成:char a[]="You are a student.";char *to=a;没有问题 printf("string a=%s\nstring b=%s\n",from,to); printf("copy string a to string b:\n"); copy_string(from,to); printf("\nstring a=%s\nstring b=%s\n",from,to); return 0;}void copy_string(char *from,char *to){ while(*to=*from) {to++; from++; }}
查看完整描述

2 回答

?
qq_追梦_26

TA贡献15条经验 获得超2个赞

其实这个问题的本质是在于const char* 和 char*的区别,前者是只能读,不可以被修改的,后者可读可写:

你的例子当中a[]本身就可以读可以写的相当于char*,而当你换成char *to = “You are a student”的时候to就变成了const char *to了因此to所拥有的空间就不能被修改了 !

查看完整回答
1 反对 回复 2015-10-26
  • 2 回答
  • 0 关注
  • 1532 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信