#include <iostream>
#include <string.h>
void main()
{
char* str3 = "Underworld";
int str_length = strlen(str3);
char* str_context = new char[str_length];
for (int i = 0; i != str_length; i++) {
str_context[i] = str3[i];
}
std::cout << str3 << std::endl;
std::cout << str_context << std::endl;
}
i expected cout << str_context
prints out UnderWorld
我以为Cout<
however, str_context cout prints out Underworld金蘇--
但是,str_CONTEXT COUT会打印出UnderWorld金蘇--
why does str_context have garbage value even if i limited size of array by new char[str_length}
?
为什么即使我用新的char[str_long}限制了数组的大小,str_context也有无用的值?
str3 cout prints out "Underworld" though
不过,str3 cout打印出了《冥界》。
更多回答
strlen
returns the length of the string, which does not include the null terminator. When you copy the contents of str3
into str_context
, you don't copy that null terminator. Then, when you pass a non-null-terminated character array to <<
, you end up with undefined behavior.
Strlen返回字符串的长度,不包括空终止符。当您将str3的内容复制到str_CONTEXT中时,您不会复制那个空终止符。然后,当您将一个非空终止的字符数组传递给<<时,您将得到未定义的行为。
even if a duplicated question your answer made me clear have a great day
即使是一个重复的问题,你的回答也让我明白,祝你有美好的一天
Also note in current C++ you should avoid new/delete whenever you can (your current code is very "C" like), in this case just use std::string
(instead of new char). std::string str3{"underworld"}; std::string context{str3};
context will be copy constructed for you (initialized with a copy of str3). std::size_t str_length = str.size();
will get the size of the str3 for you.
还要注意,在当前的C++中,您应该尽可能避免新建/删除(您当前的代码非常类似于“C”),在这种情况下,只需使用std::string(而不是new char)。Std::string str3{“Underworld”};std::字符串上下文{str3};将为您复制构造上下文(使用str3的副本进行初始化)。Std::SIZE_T STR_LENGTH=str.Size();将为您获取str3的大小。
And if you must use C strings in C++, note that you should have used strdup()
instead of all this manual coding.
如果您必须在C++中使用C字符串,请注意,您应该使用strdup(),而不是所有这些手动编码。
我是一名优秀的程序员,十分优秀!