Why the NULL character is not right after the last index of this array?

Walkbitterwyrm Lightwarg 20 Reputation points
2023-10-31T14:11:57.9366667+00:00

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?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,981 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,447 questions
{count} votes

6 answers

Sort by: Most helpful
  1. David Lowndes 2,040 Reputation points MVP
    2023-10-31T14:23:40.98+00:00

    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.


  2. RLWA32 38,956 Reputation points
    2023-10-31T14:29:13.6566667+00:00

    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.

    0 comments No comments

  3. Bruce (SqlWork.com) 52,826 Reputation points
    2023-10-31T16:19:29.76+00:00

    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

    0 comments No comments

  4. Barry Schwarz 1,746 Reputation points
    2023-10-31T16:21:20.8366667+00:00

    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.

    0 comments No comments

  5. WayneAKing 4,921 Reputation points
    2023-11-03T10:31:17.72+00:00

    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";
    
    
    • Wayne