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

后端 未结 5 2043
野趣味
野趣味 2020-12-19 06:57

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?



        
5条回答
  •  生来不讨喜
    2020-12-19 07:24

    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.

提交回复
热议问题