Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - Why can't I edit a char in a char*?

Below is an exceedingly simple example. It compiles fine using gcc on Mac OS X (Snow Leopard). At runtime it outputs Bus error: 10. What's happening here?

char* a = "abc";
a[0] = 'c';
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your code sets a to a pointer to "abc", which is literal data that can't be modified. The Bus error occurs when your code violates this restriction, and tries to modify the value.

try this instead:

char a[] = "abc";
a[0] = 'c';

That creates a char array (in your program's normal data space), and copies the contents of the string literal into your array. Now you should have no trouble making changes to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...