Modifying individual array elements
What you'll learn: How to target and change a single value stored inside an array using its index.
The Post Office Analogy
Think of an array as a row of post office boxes. When you first create an array, you’ve essentially reserved the whole row. However, an array isn't a "static" snapshot; you can walk up to any specific box at any time, take out what’s inside, and put something new in its place.
In C, we use the assignment operator (=) to do this. The key is to tell the computer exactly which "box" you are talking about by providing its index number inside square brackets.
Targeting the index
Remember that C uses zero-based indexing. This means the very first slot is 0, the second is 1, and so on. If you have an array of five integers and you want to change the very first number, you target index 0.
If you try to change a value using an index that doesn't exist (like index 10 in a 5-slot array), C won't always stop you with an error message, but your program will likely crash or behave strangely. Always stay within the boundaries you defined when you created the array.
Code Example
In the following snippet, we initialize an array with three values and then update the middle one.
#include <stdio.h>
int main() {
// Create an array with 3 integers
int scores[3] = {85, 92, 78};
// We realized the second student (index 1) earned extra credit!
// We target index 1 and assign it a new value.
scores[1] = 95;
// We can also perform math on the current value
// Let's add 2 points to the last student (index 2)
scores[2] = scores[2] + 2;
printf("New scores: %d, %d, %d\n", scores[0], scores[1], scores[2]);
return 0;
}
How it works
When you write scores[1] = 95;, the computer calculates the memory address of the second slot in the scores array and overwrites whatever was there with the number 95. The rest of the array remains untouched. This allows you to manage large collections of data while still having the surgical precision to update a single data point whenever necessary.
Key takeaway
To modify an array element, use the syntax arrayName[index] = newValue;, making sure your index is within the array's bounds.