简体   繁体   English

在gcc中显示char数组不起作用

[英]Displaying char array in gcc does not work

I wrote a piece of code and tested with gcc compiler 我写了一段代码,并用gcc编译器进行了测试

#include <iostream>

int main()
{
    char arr[ 1000 ];
    for( int index( 0 ); index < 1000; ++index )
    {
        std::cout << arr[ index ] << std::endl;
    }
    return 0;
}

I was hoping it to print the garbage values but to my surprise, it did not print anything. 我希望它能打印垃圾值,但令我惊讶的是,它什么也没打印。 When I simply changed the datatype of arr from char to int, it displayed the garbage values as expected. 当我只是将arr的数据类型从char更改为int时,它按预期显示了垃圾值。 Could somebody please explain this to me? 有人可以向我解释一下吗?

The overloads for << for character types do not treat them as integral types, but as characters. 对于字符类型, <<的重载不会将它们视为整数类型,而是字符。 If the garbage value corresponds to a printable character (eg 97, which corresponds to 'a' ), you will see it. 如果垃圾值对应于可打印字符(例如97,对应于'a' ),则将看到它。 If it doesn't (eg 0), you won't. 如果不是(例如0),则不会。 And if the garbage values correspond to some escape sequence which causes your terminal to use a black foreground on a black background, you won't see anything else, period. 并且,如果垃圾值与某个转义序列相对应,导致您的终端在黑色背景上使用黑色前景,那么您将看不到其他任何内容,即句点。

If you want to see the actual numerical values of a char (or any character type), just convert the variable to int before outputting it: 如果要查看char (或任何字符类型)的实际数值,只需在输出变量之前将其转换为int

std::cout << static_cast<int>( arr[index] ) << std::endl;

What you're trying to do has an undefined behavior . 您尝试执行的操作具有undefined behavior Some compilers will clear out the memory for you, others will leave it as it was before the creation of your buffer. 一些编译器会为您清除内存,而其他编译器会将其保留为创建缓冲区之前的状态。

Overall, this is a useless test. 总的来说,这是一个无用的测试。

Some platforms may choose, for example for security purposes, to fill the uninitialized char array with zeroes, even though it's not static and wasn't explicitly initialized. 为了安全起见,某些平台可能会选择使用零填充未初始化的char数组,即使该数组不是静态的且未明确初始化也是如此。 Therefore, that is why no garbage is showing up - your char array was just automatically initialized. 因此,这就是为什么没有垃圾出现的原因-您的char数组刚刚被自动初始化。

On your platform garbage characters don't print. 在您的平台上,不打印垃圾字符。 On another platform it might be different. 在另一个平台上,情况可能有所不同。

As an experiment try this 作为实验尝试

std::cout << '|' << arr[ index ] << '|' << std::endl;

See if anything appears between the || 查看||之间是否出现任何内容 characters. 字符。

You're getting undefined behaviour because you're attempting to use values from an uninitialised array. 由于尝试使用未初始化的数组中的值,因此出现未定义的行为。 You can't expect anything in particular to happen. 您不能指望有什么特别的事情发生。 Maybe every character happens to be a non-printing character. 也许每个字符都是非印刷字符。 Maybe it just decided that it didn't want to print anything because it doesn't like your little games. 也许它只是决定不想打印任何东西,因为它不喜欢您的小游戏。 Anything goes. 什么都行。

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

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