2

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?

1
  • 3
    This case is pretty obvious, but in the future it would help to tell us what the program is doing (other than "not working") in addition to what you expect it to do; otherwise we can only guess as to what the problem may be. Commented May 4, 2012 at 19:30

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

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

Comments

2

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);

Comments

1

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";

1 Comment

That zero escaped with a backslash is perfectly fine, it represents (char)0, which terminates the string. I don't see the reason for downvoting. +1.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.