Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - About character pointers in C

Consider this definition:

char *pmessage = "now is the time";

As I see it, pmessage will point to a contiguous area in the memory containing these characters and a '' at the end. So I derive from this that I can use pointer arithmetic to access an individual character in this string as long as I'm in the limits of this area.

So why they say (K&R) that modifying an individual character is undefined?
Moreover, why when I run the following code, I get a "Segmentation Fault"?

*(pmessage + 1) = 'K';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

String literals in C are not modifiable. A string literal is a string that is defined in the source code of your program. Compilers will frequently store string literals in a read-only portion of the compiled binary, so really your pmessage pointer is into this region that you cannot modify. Strings in buffers that exist in modifiable memory can be modified using the syntax above.

Try something like this.

const char* pmessage = "now is the time";

// Create a new buffer that is on the stack and copy the literal into it.
char buffer[64];
strcpy(buffer, pmessage);

// We can now modify this buffer
buffer[1] = 'K';

If you just want a string that you can modify, you can avoid using a string literal with the following syntax.

char pmessage[] = "now is the time";

This method directly creates the string as an array on the stack and can be modified in place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...