The following code snippet gives unexpected output in Turbo C++ compiler:
char a[]={'a','b','c'};
printf("%s",a);
Why doesn't this print abc? In my understanding, strings are implemented as one dimensional character arrays in C.
Secondly, what is the difference between %s and %2s?
This is because your string is not zero-terminated. This will work:
char a[]={'a','b','c', '\0'};
The %2s specifies the minimum width of the printout. Since you are printing a 3-character string, this will be ignored. If you used %5s, however, your string would be padded on the left with two spaces.
char a[]={'a','b','c'};
Well one problem is that strings need to be null terminated:
char a[]={'a','b','c', 0};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With