Rachit
Rachit

Reputation: 501

Code giving unexpected output in 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?

Upvotes: 2

Views: 485

Answers (5)

Saroj Sharma
Saroj Sharma

Reputation: 65

Whenever we store a string in c programming, we always have one extra character at the end to identify the end of the string.

The Extra character used is the null character '\0'. In your above program you are missing the null character.

You can define your string as

char a[] = "abc";

to get the desired result.

Upvotes: 0

user411313
user411313

Reputation: 3990

Without change the original char-array you can also use

     char a[]={'a','b','c'};
     printf("%.3s",a);
or
     char a[]={'a','b','c'};
     printf("%.*s",sizeof(a),a);
or
     char a[]={'a','b','c'};
     fwrite(a,3,1,stdout);
or
     char a[]={'a','b','c'};
     fwrite(a,sizeof(a),1,stdout);

Upvotes: 2

kist
kist

Reputation: 590

Because you aren't using a string. To be considered as a string you need the 'null termination': '\0' or 0 (yes, without quotes).

You can achieve this by two forms of initializations:

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

or using the compiler at your side:

char a[] = "abc";

Upvotes: 1

Brendan Long
Brendan Long

Reputation: 54312

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

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

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

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

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.

Upvotes: 5

Related Questions