C 語言中 char s[] 和 char *s 的區別
我們有時會看到字串使用 char s[] 構建,有時使用 char *s 構建。因此,我們在這裡要看它們是否有不同或完全相同?
存在一些差異。s[] 是一個數組,但 *s 是一個指標。例如,如果有兩個宣告,分別是 char s[20] 和 char *s,那麼使用 sizeof(),我們分別得到 20 和 4。第一個將是 20,因為它顯示該資料有 20 個位元組。但第二個僅顯示 4,因為這是一個指標變數的大小。對於一個數組,整個字串儲存在堆疊部分,但對於一個指標,指標變數儲存在堆疊部分,而內容儲存在程式碼部分。最重要的是,我們無法編輯指標型別字串。因此這是隻讀的。但我們可以編輯字串的陣列表示。
示例
#include<stdio.h> main() { char s[] = "Hello World"; s[6] = 'x'; //try to edit letter at position 6 printf("%s", s); }
輸出
Hello xorld Here edit is successful. Now let us check for the pointer type string.
示例
#include<stdio.h> main() { char *s = "Hello World"; s[6] = 'x'; //try to edit letter at position 6 printf("%s", s); }
輸出
Segmentation Fault
廣告