Overstepping array boundaries
suggest changeArrays are zero-based: the index starts at 0, and the last valid index is one less than the length. The following code skips the first element and evaluates myArray[5], which is outside the array. That access is undefined behavior. A particular run may appear to print an extra value; the program is not required to do so.
#include <stdio.h>
int main(void)
{
int x = 0;
int myArray[5] = {1, 2, 3, 4, 5}; //Declaring 5 elements
for(x = 1; x <= 5; x++) //Looping from 1 till 5.
printf("%d\t", myArray[x]);
printf("\n");
return 0;
}
One observed run printed 2, 3, 4, 5, and an additional value. That extra value is not specified.
The following demonstrates the correct way to achieve the desired output:
#include <stdio.h>
int main(void)
{
int x = 0;
int myArray[5] = {1, 2, 3, 4, 5}; //Declaring 5 elements
for(x = 0; x < 5; x++) //Looping from 0 till 4.
printf("%d\t", myArray[x]);
printf("\n");
return 0;
}
Output: 1 2 3 4 5
It is important to know the length of an array before working with it as otherwise you may corrupt the buffer or cause a segmentation fault by accessing memory locations that are out of bounds.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents