-6

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;
}
yano
  • 4,827
  • 2
  • 23
  • 35
  • 2
    because `printf` doesn't know how big your array is and keeps on printing until it finds a `NUL` char – yano Sep 13 '22 at 03:38
  • Whoops, I used the wrong duplicate. [This one](https://stackoverflow.com/questions/3767284/using-printf-with-a-non-null-terminated-string) linked from there is more appropriate. – paddy Sep 13 '22 at 05:16

1 Answers1

1

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.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38