要知道發生了什麼事,你要明白一個C程序的內存佈局。
char *s = "sample"; // Here the "sample" string is placed in
// the read only memory of the Initialized Data segment.
在這裏,您不能修改數據。 「s
」是指向char const
(「樣本」)的指針,並且您正在嘗試修改char const
。這就是爲什麼你得到bus error
錯誤。
|Stack frame of main() |
|char *s |
|-------------------------------|
|Stack frame of reverse() |
|char *end |
|char tmp |
| |
|-------------------------------|
| |
| |
| |
| |
| |
|-------------------------------|
| |
| HEAP |
| |
|-------------------------------|
| |
| UNINITIALIZED DATA (BSS) |
| |
|-------------------------------|
| |
| INITIALIZED DATA |
| |
|"sample" | |
| | |
|(Read Only)| (Read/Write) |
|-------------------------------|
| Text or Code Segment |
| |
|-------------------------------|
UPDATE 後下不涉及您的問題。但是如果你知道在C中爲所有變量分配的內存在哪裏,那麼你可以更好地編寫代碼。 下面的程序可以更好地理解C程序的內存佈局。 我沒有在圖中包含函數的命令行參數,函數參數和返回值。 想要更新這篇文章的人可以將函數的命令行參數,函數參數和返回值添加到圖中。
|Stack frame of main() |
|local_To_Main |
| | #include <stdio.h>
|-----------------------------------| #include <stdlib.h>
|Stack frame of function1() | int gVariable1 = 100;
|local_To_Function1 | int gVariable2;
|iptr | char cstring[10] = "Hello";
| \ STACK | char* cptr = "Hello World";
|------\---------------|------------| void function1(void)
| \ \|/ | {
| \ | static int j = 5;
| \ | int local_To_Function1;
| \ ^ | int *iptr;
| \ | | iptr = (int *) malloc(sizeof(int));
|------------\---------------|------| free(iptr);
| HEAP \ --- | }
| \---> |int| |
| --- | int main(void)
|-----------------------------------| {
| | static int i;
| UNINITIALIZED DATA (BSS) | int local_To_Main;
|gVariable2(initialized to 0) |
|i (initialized to 0) |
|-----------------------------------| function1();
| | return 0;
| INITIALIZED DATA | }
| |
|"Hello World" |gVariable1 =100 |
| ^ |cstring="Hello" |
| | |j=5 |
| |---<---<---- cptr |
|(Read Only) | (Read/Write) |
|-----------------------------------|
| Text or Code Segment |
| |
|-----------------------------------|
我相當肯定你的意思'的printf( 「%S \ n」,S);'。 – cHao
你應該寫'const char * s =「sample」;'。得到它了?你知道爲什麼字符串常量被稱爲常量嗎?沒有?更好地谷歌它。 – 2013-12-26 10:58:50