user2826742
user2826742

Reputation: 13

C - Array is out of Range

Considering the following:

#define SIZE 5

/* ... */

int oxen[SIZE] = {5,3,2,8};
int yaks[SIZE];
yaks[SIZE] = oxen [SIZE];   /* -->Out of range */

Can someone explain why its out of range?

Upvotes: 0

Views: 663

Answers (3)

Alex Reynolds
Alex Reynolds

Reputation: 96947

Because C is zero-indexed, oxen[SIZE] is really trying to deference a sixth element that does not exist. Use the index [SIZE-1], instead.

Upvotes: 1

Omar Khaled
Omar Khaled

Reputation: 11

because c Language can access the elements of array by their indexes thus index start from 0 to n-1 where n is a number of elements in your array so in your case u can access elements from 0 to 4 indexes if u deal with array of characters maybe this works because of null terminator '\0' also u may not get an errors and get random results because its compiler dependent :)

Upvotes: 0

xbug
xbug

Reputation: 1472

Arrays indices in C start at 0, so your oxen and yaks arrays range from 0 to SIZE-1. You're outside the allowed boundaries, as the compiler rightly warns you about.

Upvotes: 3

Related Questions