-4
#include<stdio.h>
int main()
{
    char name[5] = {'A', 'B', 'C', 'D', 'E'};
    printf(name);
    return 0;
}

** I am learning arrays and wanted to print this array 'name' and the code runs and the output is like 'ABCDE└‼╠'. Why is this └‼╠ symbol coming?

jps
  • 20,041
  • 15
  • 75
  • 79
  • 1
    Because you have forgotten that strings in C are really called ***null-terminated** strings*. All string-handling standard functions uses the `'\0'` null-terminator character to know the end of the string. – Some programmer dude Sep 27 '22 at 14:12
  • 2
    Because `name` is not a *string*: it does not have a required `'\0'` byte anywhere in the array (it's a valid array, of course, just not a valid string). – pmg Sep 27 '22 at 14:12
  • But if I change my array to char name[5] = {'Y', 'A', 'S', 'H'}; It is giving output "YASH" only – Dhruv Yadav Sep 27 '22 at 14:18
  • That's because the compiler will make sure to initialize the remaining elements with zero, which is the same as the null-terminator. – Some programmer dude Sep 27 '22 at 14:24
  • Please don't pick a closed post as duplicate target, that's never the correct to go. I now changed it to a "canonical" dupe for this FAQ. – Lundin Sep 27 '22 at 15:05

1 Answers1

2

Because you did not NULL-Terminate your string.

function printf will print a string until it finds a \0 byte that indicates the end of the string.

You did not put in a \0 byte, so printf continues to print until it encounters a terminator just by sheer luck.

In this case, it looks like it printed 3 more characters of random bytes until it happened to find the end of string marker.

To fix it, do this:

char name[6] = {'A', 'B', 'C', 'D', 'E', '\0'};
// Changed the size to 6, and added the NULL-terminator (aka. End-of-String Marker)
abelenky
  • 63,815
  • 23
  • 109
  • 159