First look at a program like this:
1#include <iostream>2 using namespacestd;3 intMain () {4 Char*s ="Hello World";5 6cout << S <<Endl;7s[0] ='B';8cout << S <<Endl;9 return 0;Ten}
The result of compiling the run under VS2013 is:
What's the reason?
The memory in the computer is partitioned (Segment) when it is used for programming, and is divided into: stack, heap, global (static), literal constant, and code area.
Strings defined with *s are stored in the literal constant area, which is defaulted to the const type and therefore cannot be modified.
When the program is changed to the following, you can get the desired effect.
1#include <iostream>2 using namespacestd;3 intMain () {4 //char *s = "Hello World";5 CharS[] ="Hellow World";6cout << S <<Endl;7s[0] ='B';8cout << S <<Endl;9 while(1);Ten return 0; One}
Operation Result:
By printing the first address of the string in two ways, it is easy to spot the problem.
The Modified program:
1#include <iostream>2 using namespacestd;3 intMain () {4 Char*S1 ="Hello World";5 CharS2[] ="Hellow World";6cout << &s1 <<Endl;7 //s[0] = ' B ';8cout << &s2 <<Endl;9cout << &main <<Endl;Ten while(1); One return 0; A}
Operation Result:
The string defined by the string is found to be placed in a very forward address space (the stack area), and the string defined by the pointer is close to the main function address.
Const in C + +