打印char数组C ++ [英] Printing char arrays c++
问题描述
我在C ++中玩弄c字符串,发现一些我不终止char
数组时不了解的行为.
char strA[2] = {'a','\0'};
char strB[1] = {'b'};
cout << strA << strB;
我希望它会打印ab
,但是会打印aba
.如果我改为在strA
之前声明strB
,它将按预期工作.有人可以解释这是怎么回事吗?
这是未定义的行为,您很幸运地替换了这两个数组的声明对您有用.让我们看看您的代码中发生了什么:
char strA[2] = {'a','\0'};
创建一个可以像字符串一样对待的数组-它以 null终止.
char strB[1] = {'b'};
创建一个数组,该数组不能被视为字符串,因为它缺少空终止符'\0'
.
std::cout << strA << strB;
第一部分是<< strA
,可以正常工作.因为strA
被当作const char*
对待,所以它会打印a
,作为std::ostream& operator <<
的参数提供的参数将被用于打印每个字符,直到遇到空终止符为止.. >
那会发生什么?然后,执行<< strB
(实际上,与将该行分为两个单独的std::cout <<
调用相比,实际上有点不同,并且更复杂,但是在这里没关系).它也被视为const char*
,,预计将以提到的'\0'
结尾,但不是...
这会导致什么?您很幸运,内存中'\0'
之前(还是-随机)只有一个字符,这停止了(可能接近无限)打印过程.
为什么,如果我改为在
strA
之前声明strB
,它会按预期工作?
那是因为您很幸运,编译器决定在strB
之后声明您的strA
,因此,在打印strB
时,它会打印包含它的所有内容并打印strA
,最后具有空终止符.这不能保证.避免使用char[]
表示和打印字符串.请改用std::string
,它会为您处理空终止符.
I was playing around with c strings in c++ and found some behavior I don't understand when I don't terminate a char
array.
char strA[2] = {'a','\0'};
char strB[1] = {'b'};
cout << strA << strB;
I would expect this to print ab
, but instead it prints aba
. If I instead declare strB
before strA
, it works as expected. Could someone explain what's going on here?
This is undefined behaviour and you simply are lucky that replacing the declaration of these 2 arrays works for you. Let's see what is happening in your code:
char strA[2] = {'a','\0'};
Creates an array that can be treated like a string - it is null terminated.
char strB[1] = {'b'};
Creates an array that cannot be treated like a string, because it lacks the null terminating character '\0'
.
std::cout << strA << strB;
The first part, being << strA
, works fine. It prints a
since strA
is treated as a const char*
, which provided as an argument for std::ostream& operator <<
will be used to print every character untill the null terminating character is encountered.
What happens then? Then, the << strB
is being executed (actually what happens here is a little different and more complicated than simply dividing this line into two, separate std::cout <<
calls, but it does not matter here). It is also treated as a const char*
, which is expected to be ended with mentioned '\0'
, however it is not...
What does that lead to? You are lucky enough that there randomly is only 1 character before (again - random) '\0'
in memory, which stops the (possibly near-infinite) printing process.
Why, if I instead declare
strB
beforestrA
, it works as expected?
That is because you were lucky enough that the compiler decided to declare your strA
just after the strB
, thus, when printing the strB
, it prints everything that it consists + prints strA
, which ends with null terminating character. This is not guaranteed. Avoid using char[]
to represent and print strings. Use std::string
instead, which takes care of the null terminating character for you.
这篇关于打印char数组C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!