简体   繁体   English

代码在c中给出意外输出

[英]Code giving unexpected output in c

The following code snippet gives unexpected output in Turbo C++ compiler: 以下代码片段在Turbo C ++编译器中提供了意外输出:

     char a[]={'a','b','c'};
     printf("%s",a);

Why doesn't this print abc ? 为什么不打印abc In my understanding, strings are implemented as one dimensional character arrays in C. 根据我的理解,字符串在C中实现为一维字符数组。
Secondly, what is the difference between %s and %2s ? 其次, %s%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. %2s指定打印输出的最小宽度。 Since you are printing a 3-character string, this will be ignored. 由于您要打印3个字符的字符串,因此将被忽略。 If you used %5s , however, your string would be padded on the left with two spaces. 但是,如果您使用了%5s ,则您的字符串将在左侧填充两个空格。

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

一个问题是字符串需要以null结尾:

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

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

Because you aren't using a string. 因为您没有使用字符串。 To be considered as a string you need the 'null termination': '\\0' or 0 (yes, without quotes). 要被视为字符串,您需要'空终止':'\\ 0'或0(是的,没有引号)。

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

Whenever we store a string in c programming, we always have one extra character at the end to identify the end of the string. 每当我们在c编程中存储一个字符串时,我们总是在末尾有一个额外的字符来标识字符串的结尾。

The Extra character used is the null character '\\0' . 使用的Extra字符是null字符'\\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. 获得理想的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM