开发者

C++ pointer explanation

char* pstr[] = { "Robert Redford", // Initializing a pointer array
                 "Hopalong Cassidy",
                 "Lassie",
                 "Slim Pickens",
                 "Boris Karloff",
                 "Oliver Hardy"
               };

If I write like below:

*pstr[0] = 'X';

The program can compile but crashes when this statement is executed. Why? I thought *p开发者_如何学Cstr[0] is 'R' so that I can change from 'R' to 'X'. Thanks!


The compiler should have warned you:

warning: deprecated conversion from string constant to 'char*''

What you're doing here is assigning some constant char arrays to a mutable char pointer, much like:

const char[] astring = "ababa";
char* mutablestring = astring; // shouldn't be possible
mutablestring[0] = 'o'; // change 'readonly' location

The result is, at run time, a pointer that points into your binary, and that you're writing to. But that's readonly memory, so.. crash.


You are making a pointer to an array of const char*s. So pstr[0] is pointing to a const char* and you can't change it's value.

It's a good programming practice to write this code in this way so you'll get a compiler error if you try to change the value instead of runtime error:

char* const pstr[] = { "Robert Redford", // Initializing a pointer array
                 "Hopalong Cassidy",
                 "Lassie",
                 "Slim Pickens",
                 "Boris Karloff",
                 "Oliver Hardy"
               };


The string literals are constants, so you cannot change them.

Conversion from const char* to char* is allowed just to allow old C code from the time before C got const.


pstr is an array with const *char elements. The result of modifying read-only memory is undefined. If you know the max size of each string you can declare pstr like so

char pstr[][32] = { "Robert Redford",
                 "Hopalong Cassidy",
                 "Lassie",
                 "Slim Pickens",
                 "Boris Karloff",
                 "Oliver Hardy"
               };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜