Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code giving unexpected output in c

Tags:

c

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?

like image 578
Rachit Avatar asked Jul 22 '26 14:07

Rachit


2 Answers

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.

like image 132
Sergey Kalinichenko Avatar answered Jul 25 '26 08:07

Sergey Kalinichenko


char a[]={'a','b','c'};

Well one problem is that strings need to be null terminated:

char a[]={'a','b','c', 0};
like image 42
Brendan Long Avatar answered Jul 25 '26 08:07

Brendan Long