Setting values in arrays
suggest changeAccessing array values is generally done through square brackets:
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];
Because the operands of + are commutative, the following expressions are equivalent:
*(array + 4) = 5;
*(4 + array) = 5;
so these statements are equivalent as well:
array[4] = 5;
4[array] = 5; /* Weird but valid C ... */
and so are these:
val = array[4];
val = 4[array]; /* Weird but valid C ... */
C does not check array bounds. Accessing an element outside the array is undefined behavior:
int val;
int array[10];
array[4] = 5; /* ok */
val = array[4]; /* ok */
array[19] = 20; /* undefined behavior */
val = array[15]; /* undefined behavior */
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents