传递不是空终止字符串的printf意想不到的结果值 [英] Passing not null terminated string to printf results in unexpected value

查看:155
本文介绍了传递不是空终止字符串的printf意想不到的结果值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个C程序给出了一个怪异的结果:

This C program gives a weird result:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
   char str1[5] = "abcde";
   char str2[5] = " haha";

   printf("%s\n", str1);
   return 0;
}

当我运行这个code我得到:

when I run this code I get:

abcde haha

我只想打印第一个字符串可以从code可以看出。结果
它为什么他们同时打印?

I only want to print the first string as can be seen from the code.
Why does it print both of them?

推荐答案

ABCDE其实是因为在C字符串的空终止字符的6字节长。当你这样做:

"abcde" is actually 6 bytes long because of the null terminating character in C strings. When you do this:

char str1[5] = "abcde";

您没有存储空终止字符,所以它不是一个适当的字符串。

You aren't storing the null terminating character so it is not a proper string.

当你这样做:

char str1[5] = "abcde";
char str2[5] = " haha";
printf("%s\n", str1);

有恰好是与第二串之后的第一个存储的,虽然这不是必需的。通过调用的printf 在不是空终止您已经引起未定义行为的字符串。

It just happens to be that the second string is stored right after the first, although this is not required. By calling printf on a string that isn't null terminated you have already caused undefined behavior.

更新:

如由clcto这可以通过不明确指定数组的大小并让编译器确定它基于该串的可以避免评论指出:

As stated in the comments by clcto this can be avoided by not explicitly specifying the size of the array and letting the compiler determine it based off of the string:

char str1[] = "abcde";

或使用一个指针,而不是是否适合你的使用情况,虽然他们是不一样的:

or use a pointer instead if that works for your use case, although they are not the same:

char *str1 = "abcde";

这篇关于传递不是空终止字符串的printf意想不到的结果值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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