Sahil Silare
Sahil Silare

Reputation: 333

Can we use last element of an array?

I have an array defined as arr[5]. Can I fill and use the last element, like arr[5]=1000? If yes, where will the '\0' be stored in the array? Further, isn't I am using the memory I've not declared?

Upvotes: 1

Views: 1267

Answers (2)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29955

You cannot use arr[5] if it was it is defined to have 5 elements, because in that case arr[5] is not the last element.
Example:

int arr[5] = {10, 11, 12, 13, 14}

Here, the last element is arr[4] and its value is 14, and trying something like arr[5] is undefined. It might work on your compiler and your machine, but relying on undefined behavior is a very bad idea. See this for further explanation

'\0' as the last element is something C style null-terminated character arrays have. In that case the last element is '\0' (hence the name null terminated). That is still not out of range tho, the very last element is just '\0'.
Example:
char arr[5] = "food";
Here arr[4] is implicitly assigned to '\0'. Assigning something else here is completely okay, but you will have problems printing it as a null-terminated string.

Upvotes: 3

Ron
Ron

Reputation: 15501

You can not use arr[5] as that is not the last element of the array. That would invoke undefined behavior as you would read out of bounds. The last element of an array is arr[4].

The null character that is \0 is not something that automatically gets inserted into every array. It is always inserted into a string literal but not your everyday, user-defined array.

For example, this will work:

char arr[] = "Hello"; // array of 6 elements initialized with a string literal
                      // 5 for the characters plus 1 for the invisible \0
std::cout << arr[5];  // OK

Whereas this will not:

int arr[5] = { 1, 2, 3, 4, 5 }; // user defined array of 5 elements
std::cout << arr[5];            // Not OK! Reading out of bounds == UB

as there is no such thing as arr[5], nor is there a null character appended to the array of 5 ints.

Upvotes: 6

Related Questions