Search code examples
carraysinitializationc-strings

Assignment after initialization to specific index in an array


After assigning 26th element, when printed, still "Computer" is printed out in spite I assigned a character to 26th index. I expect something like this: "Computer K "

What is the reason?

#include <stdio.h>
int main()
{
  char m1[40] = "Computer";
  printf("%s\n", m1);   /*prints out "Computer"*/
  m1[26] = 'K';
  printf("%s\n", m1);   /*prints out "Computer"*/
  printf("%c", m1[26]); /*prints "K"*/
}

Solution

  • Whenever you partially initialize an array, the remaining elements are filled with zeroes. (This is a rule in the C standard, C17 6.7.9 §19.)

    Therefore char m1[40] = "Computer"; ends up in memory like this:

    [0] = 'C'
    [1] = 'o' 
    ... 
    [7] = 'r'
    [8] = '\0' // the null terminator you automatically get by using the " " syntax
    [9] = 0    // everything to zero from here on
    ... 
    [39] = 0
    

    Now of course \0 and 0 mean the same thing, the value 0. Either will be interpreted as a null terminator.

    If you go ahead and overwrite index 26 and then print the array as a string, it will still only print until it encounters the first null terminator at index 8.

    If you do like this however:

    #include <stdio.h>
    
    int main()
    {
      char m1[40] = "Computer";
      printf("%s\n", m1); // prints out "Computer"
      m1[8] = 'K';
      printf("%s\n", m1); // prints out "ComputerK"
    }
    

    You overwrite the null terminator, and the next zero that happened to be in the array is treated as null terminator instead. This code only works because we partially initialized the array, so we know there are more zeroes trailing.

    Had you instead written

    int main()
    {
      char m1[40];
      strcpy(m1, "Computer");
    

    This is not initialization but run-time assignment. strcpy would only set index 0 to 8 ("Computer" with null term at index 8). Remaining elements would be left uninitialized to garbage values, and writing m1[8] = 'K' would destroy the string, as it would then no longer be reliably null terminated. You would get undefined behavior when trying to print it: something like garbage output or a program crash.