You've got an array with 5 elements, that's indexes 0 to 4.
5 & 6 are past the end of the array.
Any output you get is fortunate, it could even crash.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am using the following program to check the position of the NULL character in a character array. Usually it should be at the 'n; index of an array with size 'n'. But this program shows the NULL character at n+1 index.
#include <stdio.h>
int main()
{
char a[5] = {'a', 'b', 'c', 'd', 'e'};
printf("Character at index 5: %c\n", a[5]);
printf("Character at index 6: %d", a[6]);
return 0;
}
Output:
Character at index 5: Ç
Character at index 6: 0
What is giving such an output and why the 'Ç' character is at index 5?
You've got an array with 5 elements, that's indexes 0 to 4.
5 & 6 are past the end of the array.
Any output you get is fortunate, it could even crash.
Another example of undefined behavior. Valid indices of an array with n elements are 0 to n-1;
Furthermore, there is no guarantee that a null terminator is always present for a char array. Initializing an array with a string literal is what introduces a null terminator.
if the variable a is to be use as a string, then its a bug in your code. you forgot the null terminator:
char a[6] = {'a', 'b', 'c', 'd', 'e', 0}; // null terminate
or
char* s = "abcde"; // create a 6 byte literal as the null is added
There is NO terminator in your array. You specifically defined the array to have five elements. You initialized each of those elements with the letters 'a' through 'e'. There is no room for a terminator.
Any assertion you make about data outside the array is based on undefined behavior and therefore meaningless.
Additional examples:
//not valid in C++, valid in ISO C where a will be 5 chars with no NUL
char a[5] = "ancde";
//valid in C++ and valid in ISO C - a will be 6 chars with NUL at end
char a[] = "ancde";