为什么这个code工作用C [英] why this code works in C
问题描述
的#include<&stdio.h中GT;诠释主(){字符数组[2];
阵列[0] =Q;
阵列[1] ='A';
的printf(%S,数组);返回0;
}
如果你问我这个code不应该工作。 printf的打印阵列[2]就像字符串,但它不是一个字符串。当我执行它,它完美的作品。你能解释一下为什么?
当我执行它,它完美的作品。
块引用>您刚刚得到(联合国)幸运:你的code展品的未定义行为的,因为它可以让
的printf
的%S
参数流失的字符序列的结束是不是空终止。在C A字符串
字符
的序列,其中必须有一个值为多余的字符0
,所谓空终止。这是一个令没有明确的行为您code的工作:字符数组[3];
阵列[0] =Q;
阵列[1] ='A';
数组[2] ='\\ 0';#include <stdio.h> int main(){ char array[2]; array[0] = 'q'; array[1] = 'a'; printf("%s",array); return 0; }
if you ask me this code should not work. printf prints array[2] like string but it's not a string. When i execute it, it works perfectly. Can you explain why?
解决方案When i execute it, it works perfectly.
You just got (un)lucky: your code exhibits undefined behavior, because it lets the
printf
's%s
parameter run off the end of the sequence of characters that is not null-terminated.A string in C is a sequence of
char
, which must have an extra character with the value0
, called the null terminator. Here is a way to make your code work without undefined behavior:char array[3]; array[0] = 'q'; array[1] = 'a'; array[2] = '\0';
这篇关于为什么这个code工作用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!