c++指针问题

来源:百度知道 编辑:UC知道 时间:2024/09/19 16:45:50
###############################
#include<iostream>
int main()
{
char *a = "Srring";
*(a+1) = 't';
cout << a << endl;
return 0;
}

###############################
#include<iostream>
int main()
{
char *a;
char b[] = "Srring";
a = b;
*(a+1) = 't';
cout << a << endl;
return 0;
}
两个程序在汇编级上有什么不同?为什么第一个程序不能运行,提示一个内存地址不能为"written",谢谢

第一个程序 a指向的内容是一个常量,所以不可更改

第二个程序,为b分配了空间,又让a指向b指向的内存,所以是可以更改的

下面是对这个问题的测试代码,
#include <iostream>
#include <typeinfo>
using namespace std;

#include<iostream>
int main()
{
char a[] = "String"; //a的类型显示 char* ,指向的内容在变量区
*(a+1) = 't';//允许
cout<<typeid(a).name()<<endl;

char *b= "String"; //b的类型显示 char* ,指向的内容在常量区
// *(b+1) = 't';//不允许,运行时报错
cout<<typeid(b).name()<<endl;

const char c[] = "String"; //c的类型显示 char const* ,
//指向的内容在变量区,但是被由于c被说明为指向常
//所以用c来使用指向的内容,并试图改变时,在编译时报错
//如果用强行手段通过编译的话,在运行时不出错(推测)
// *(c+1) = 't';//不允许,编译时报错
cout<<typeid(c).name()<<endl;

const char *d = "String"; //d的类型显示 char const* ,
//指向的内容在常量区,d也被说明为指向常
//所以用d来使用指向的内容,并试图改变时,在编译时报错