目录
摘要
记得之前看过一篇文章说所有的指针其实都可以视为一个int类型,这句话催生了我很多想法,这篇博文即为其一。
示例
- 示例代码:
#include<iostream>
using namespace std;
int main()
{
const char str[] = "123456";
cout << str << endl;
char* p = (char*)(int(str));
*p = 48; //0的ASCII
cout << str << endl;
return 0;
}
- 编译可以通过,运行也正常;运行结果:
- 分析
- 可以看到原本定义为const char的str[]的第一个字符"1"被程序在运行时修改为“0”。
- 显然重点在于 char* p = (char*)(int(str));
- 在代码中声明为const限制的变量,其实在内存层面和没有const的是一样的。
- 区别在于如果声明为const,则编译器会在编译时检查是否有对这个变量进行修改,但它不保证运行时不会被修改,因此可以用间接的方法去修改它。
- 指针存放的地址可以看做是一个int类型的值,因此显式把const char*转为int,再转为char*即可,接着我们就可以用char* p来修改身为const char的str了。
- 这不仅对于const char的数据,对于其他声明为const的数据都可以用这个方法去修改。
- 特例:
- 有些const变量(如const int)由于编译器会优化,采用宏定义直接替代,然后运行时也是可以执行修改,虽然不会报错,但修改是没有效果的,这个时候如果真要修改,得修改程序运行时代码区。
不可修改的特例
- 如果我们把str的声明由 const char[] 改为 const char * 呢?
- str声明为 const char[] 时:
- str是一个数组,数组大小取决于初始化的内容的长度,即后面"123456"的长度,除了6个数字外,还有末尾1个 "\0" 的结束符,因此是7个长度;即str的类型是const char[7]。
- 由于是在main函数内声明的,因此存放是在栈上的。
- str声明为 const char*时:
- str是一个指向const char的指针。
#include<iostream>
using namespace std;
int main()
{
const char* str = "123456";
cout << str << endl;
char* p = (char*)(int(str));
*p = 48; //0的ASCII
cout << str << endl;
return 0;
}
- 此时编译可以通过,但运行时报错;运行结果:
- 此时在用p修改str时出现写入失败,那同为const char的str,为什么这里就不能修改呢?
- 因为这里是把str声明为一个指向const char的指针,字符串“123456”是位于静态常量区的一块内存,静态常量区是程序运行时也不可修改的,而str就指向了这块内存,因此修改就报错了。
- 但上面的例子不一样,声明为const char str[]时,是给str分配了一块内存,然后把字符串"123456“写到这块内存中,由于这是在栈上的,是可以修改的,因此虽然声明是const char,但只是编译时会检查你有没有去修改它,有则不会编译通过。显然我们显示转换类型成功绕过了编译器的检查。
写在最后
* c++本身也提供了一些方法可以去掉str的const限制:比如const_cast<>,它的使用方法在百度上很多,如果需要请自行百度了解。
* 指针着实是相当有意思的东西。
A wonderful ensemble for budding scholars — or simply smarty-pants — this sensible outdated owl Halloween costume provides any child who wears it a realizing look.
By his work with his father, Clarke was uncovered to many colleges of art however Art Nouveau in particular.
BPD is one of the vital stigmatised and misunderstood mental health conditions and its devastating effect may be present in a thousand untold stories by those who dwell with it.
Weetabix is a biscuit-formed breakfast cereal that is available in packets of two.
Use residential heat pump for pool heating?
There’s one Toys’R’Us shops in Kitakyushu, in the Aeon Mall next to the closed derelict Area World amusement park.
Osborne, Chris (eleven Might 2014).
Angels appear in the outer lights and people on the left increase a soul up from the depths with the phrases “Out of the deep have I referred to as unto Thee” and on the correct angels guide a soul up a steep and rocky path to the shining city above with the phrases “Thou wilt present me the way in which of Life”.
Free Spirit” With Cowl Art & Launch Date”.
You could find a wide array of anime room decor at specialty on-line shops, together with Japanese retailers.
The one required components are lasagna noodles and cheese, cheese and extra cheese.
Upon becoming a member of the membership, he acquired a quantity thirty-one shirt for the side.
While the heat pump is working, it’s regular for condensation water to drip from it – particularly in humid circumstances.
Upon becoming a member of the membership, he acquired a quantity thirty-one shirt for the side.
This is in distinction to structural parts corresponding to a roof’s decking or rafters that serve solely a roofing or structural perform and thus do not qualify for the credit.
The colour scheme is actually the identical as the standard unique American colors.
The rooster emerges with a sweet and sticky shell.
If still you want to put it to use, that you must take some measures so as to to do.
They’re set in the two-mild window in the north aisle; one light represents the Blessed Virgin Mary, and the other reveals Saint Philip Howard.
Our love for this cheesy consolation food achieved a whole new stage after Kraft Foods launched the Kraft Macaroni and Cheese Dinner in 1937, a boxed macaroni and cheese that appealed to busy housewives within the U.S.
This is wonderful! The details provided is highly beneficial, and it was articulate. Thank you for making the effort to compose this.
I’m amazed, I must say. Rarely do I come across a blog that’s equally educative and entertaining, and without a doubt, you have hit the nail on the head. The problem is an issue that too few men and women are speaking intelligently about. I am very happy I found this during my hunt for something relating to this.
A typewriter’s ability to hit the precise spot on a type can typically surpass that of a printer.
Сервисный центр предлагает ремонт macbook 2017 ремонт macbook 2017 в петербурге
Сервисный центр предлагает замена переднего стекла xiaomi redmi note 7 pro замена дисплея xiaomi redmi note 7 pro
The inhabitants of the commune are referred to as Arconceyens or Arconceyennes in French.
A research reveals that 60 of the youngsters (thirteen to 17 years) have admitted that web addiction has become a real drawback.
An urge to resolve this conflict later spurred Clarke to embrace the most reducing-edge glass know-how.
David Hytner; Dominic Fifield (1 April 2008).
Nevertheless, most writers declare that they might have been producing copies of glass objects from Egypt.
For essentially the most entry, you could set up each a lifting lid and hinged doors.
She is in a flowing hooped dress, with a darkish shawl and a parasol.
Unaffiliated with any particular church, denomination or different entity, the Christian ministry creates Sunday Faculty supplies, offering complete lesson plans along with concepts for bulletin boards, crafts, object talks, games, skits, stories, songs, educating suggestions, and other assets.
In any case, the goal is the artwork of crafting words, and the instruments are solely devices in the fingers of the maestro – you.
Personalized gadgets that reflect their favorite collection or a present card to an anime merchandise shop can be considerate.
Particular Early Bird Admission: $10.00 (accessible 11 AM Friday).
I don’t remember talking with the GP, but do recall being transferred to another room where three unusual individuals sat in excessive back chairs watching me as I paced the flooring.
The manufacturing unit comprises eight furnaces that run continuously.
During their quest he finds himself falling for her but struggles with his emotions as a consequence of his impending return to the Water Kingdom.
Each time one thing comes in that has to be taken to your sales space, there’s a minimum cost of usually about $200 or extra.
The next time I read a blog, I hope that it does not disappoint me as much as this one. I mean, I know it was my choice to read, however I actually believed you would have something helpful to talk about. All I hear is a bunch of whining about something that you could fix if you were not too busy looking for attention.
Next time I read a blog, I hope that it won’t disappoint me just as much as this particular one. I mean, I know it was my choice to read, nonetheless I really thought you would probably have something helpful to talk about. All I hear is a bunch of crying about something you could fix if you were not too busy searching for attention.
This post is fantastic. I gained plenty from going through it. The information is extremely informative and arranged.
You made some decent points there. I checked on the net for more information about the issue and found most people will go along with your views on this website.
Greetings! Very useful advice in this particular post! It is the little changes which will make the biggest changes. Many thanks for sharing!
Сервисный центр предлагает ремонт телефона maxvi недорого ремонт телефонов maxvi на дому
Dsouza, Stanislaus P (31 July 2010).
Business Commonplace India. Enterprise Customary.
I’m very happy to uncover this site. I wanted to thank you for your time just for this wonderful read!! I definitely really liked every part of it and i also have you book marked to look at new stuff in your blog.
Сервисный центр предлагает сервис ремонта посудомоечных машин beko мастерские ремонта посудомоечных машин beko