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
100 views
in Technique[技术] by (71.8m points)

forbiddens in string literals in C

In the K&R book page 104, I came across this statement:

char amessage[] = "now is the time"; //an array
char *pmessage = "now is the time";  //a pointer

Individual characters within the array may be changed but amessage will always refer to the same storage. The pmessage pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents...

So, would this be the error they meant in both cases?

For the array,

amessage[] = "allocate to another address"; //wrong?

For the pointer,

pmessage[0] = 'n'; //wrong?

I just want to know when one is going against these rules.

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
/* OK, modifying an array initialized by the 
 * elements of a string literal */
amessage[0] = 'n';

/* not OK, modifying a string literal.
 * String literals are non-modifiable */
pmessage[0] = 'n';

Note that in C you cannot assign arrays, so if you want to copy an array use memcpy function or use strcpy function to copy a string.


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

...