Overstepping array boundaries

suggest change

Arrays are zero-based, that is the index always starts at 0 and ends with index array length minus 1. Thus the following code will not output the first element of the array and will output garbage for the final value that it prints.

#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;
}

Output: 2 3 4 5 GarbageValue

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents