一個非常基本的C問題。爲什麼以下兩個命令會導致創建具有不同大小的字符串?C基礎:比較「* char」和「char [x]」創建字符串
如下所示,方法1創建一個大小爲8字節的字符串,方法2創建一個大小爲5字節的字符串。
很困惑,爲什麼方法1是創建的大小爲8個字節的字符串...
(我已經看到了這些帖子:Difference of sizeof between char* x and char x[]和What is the difference between char s[] and char *s?除非我有一個閱讀,理解失效,它並沒有真正解決方法的原因1創建的大小爲8個字節的字符串。據響應,它似乎是方法1,應創造的4個字節大小的指針)
方法1:
char *string = "ABCD";
方法2:
char string2[5] = "ABCD";
例如,當我運行下面的程序時,我得到如下所示的輸出。
#include <stdio.h>
int main(int argc, char *argv[])
{
char *string = "ABCD";
printf("Based on \"char *string = \"ABCD\":\n");
printf("Size of string: %ld\n",sizeof(string));
printf("Size of each element of string: %ld\n",sizeof(string[0]));
printf("String: %s\n\n", string);
char string2[5] = "ABCD\0";
printf("Based on \"char string2[5] = \"ABCD\":\n");
printf("Size of string: %ld\n",sizeof(string2));
printf("Size of each element of string: %ld\n",sizeof(string2[0]));
printf("String: %s\n\n", string2);
return 0;
}
輸出上述程序的:
[C中char s \ [\]和char \ * s有什麼區別?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – 2014-10-08 22:54:42
另一個可能的愚蠢:http://stackoverflow.com/questions/15538210/sizeof-a-pointer – 2014-10-08 23:32:20
另外,對於'char string3 [] =「ABCDE」;'(沒有聲明大小)'sizeof(string3)== 6'(5個字母+ nul) – 2014-10-08 23:53:22