Null terminator in char arrays in c

Viewed 43

my question is I have created a char array of size 4.if i assigned values as below in the code without specifying the null character.How does it prints garbage values after the first four elements when the size of the char array is 4.

#include<stdio.h>

int main(){
  char array[4];

  array[0] = 'J';
  array[1] = 'O';
  array[2] = 'h';
  array[3] = 'n';

  printf("%s\n",array);

  return 0;
}
1 Answers

You told printf() that you want it to print a string with %s but you passed it an array of chars. A string is an array of chars that is terminated by a '\0'. It may print garbage, as you found, or it that may crash the program (undefined behavior).

If you want to print an array of chars you want to use the format string %.4s in this case.

Related