Search⌘ K

Writing to Arrays

Learn how to store values in an array after it has been declared as well as at the time of declaration.

Assigning values to array cells

A memory location indexed by an array (for example grades[3]) is called a cell of that array. Just like we index an array to retrieve the value stored in it, we can also write to the same cell.

We can assign the integers 1 through 5 to the cells in our grades array like this:

C
#include <stdio.h>
int main(void)
{
int grades[5];
int i;
for (i = 0; i < 5; i++) {
grades[i] = i+1;
printf("grades[%d] = %d\n", i, grades[i]);
}
return 0;
}

What can be dangerous however, is that we can also ask C to assign values to memory locations beyond the bounds of an array and C won’t complain:

C
#include <stdio.h>
int main(void)
{
int grades[5];
grades[5] = 999;
grades[500] = 12345;
printf("grades[500] = %d\n", grades[5]);
printf("grades[500] = %d\n", grades[500]);
return 0;
}

The reason this is ...