#include <stdio.h>
#include <string.h>
void main(){
char sss[0]; //array with 0 elements
sss[0]= 'h'; sss[1]= 'o'; sss[2]= 'w'; //how does this line compile wihtout error?
printf("sss after 3 chars added: %s\n", sss);
strcpy(sss, "n");
printf("sss after strcpy: %s\n", sss);
strcat(sss, " stuff");
printf("sss after strcat: %s\n", sss);
}
在這裏,我聲明瞭一個大小爲0的字符數組'sss'。因此,它將無法將任何字符賦值給任何元素。但是,數組的行爲就像一個動態分配的數組,允許分配任意數量的字符。上面的代碼產生以下輸出。C字符數組(C字符串)動態?
sss after 3 chars added: how
sss after strcpy: n
sss after strcat: n stuff
我以爲C是嚴格的數組分配,並期望它拋出「數組大小超出範圍」的錯誤。爲什麼/這是怎麼發生的?
請參閱:http://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds –
'「數組大小超出範圍」錯誤「你從哪裏得到這個想法,甚至是C中的一件事? – John3136
sss只是一個指針。和sss [X]相當於*(sss + X) –