为什么这个code工作用C [英] why this code works in C

查看:119
本文介绍了为什么这个code工作用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 value 0, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆