在陣列中設定值

訪問陣列值通常通過方括號來完成:

int val;
int array[10];

/* Setting the value of the fifth element to 5: */
array[4] = 5;

/* The above is equal to: */
*(array + 4) = 5;

/* Reading the value of the fifth element: */
val = array[4];

作為+操作符可操作的運算元的副作用( - >可交換法則),以下是等效的:

*(array + 4) = 5;
*(4 + array) = 5;

所以下一個陳述是等價的:

array[4] = 5;
4[array] = 5; /* Weird but valid C ... */

那兩個也是:

val = array[4];
val = 4[array]; /* Weird but valid C ... */

C 不執行任何邊界檢查,訪問宣告的陣列之外的內容是未定義的( 訪問超出已分配塊的記憶體 ):

int val;
int array[10];

array[4] = 5;    /* ok */
val = array[4];  /* ok */
array[19] = 20;  /* undefined behavior */
val = array[15]; /* undefined behavior */