“"的行为是什么?+ 数字和为什么 c++ 编译它?
在下面的代码中,我成功编译了它,但我不明白为什么对于某些数字值程序崩溃,而对于其他值却不是.有人能解释一下用编译器使用的 char* 添加 long int 的行为吗?
In the code below i successfully compile it but i can't understand why for certain values of number the program crash and for other values it's not. Could someone explain the behavior of adding a long int with a char* that the compiler use?
#include <iostream>
int main()
{
long int number=255;
std::cout<< "Value 1 : " << std::flush << ("" + number) << std::flush << std::endl;
number=15155;
std::cout<< "Value 2 : " << std::flush << ("" + number) << std::flush << std::endl;
return 0;
}
测试结果:
Value 1 : >
Value 2 : Segmentation fault
注意:我不是在寻找如何添加带数字的字符串的解决方案.
Note: I'm not looking for a solution on how to add a string with a number.
推荐答案
在 C++ 中,""
是一个 const char[1]
数组,其中 decays 变成一个 const char*
指针,指向数组的第一个元素(在这种情况下,字符串文字的 ''
nul 终止符).
In C++, ""
is a const char[1]
array, which decays into a const char*
pointer to the first element of the array (in this case, the string literal's ''
nul terminator).
将整数添加到指针执行指针算术,这会将指针中的内存地址提前声明指针类型的指定元素数量(在这种情况下,char
).
Adding an integer to a pointer performs pointer arithmetic, which will advance the memory address in the pointer by the specified number of elements of the type the pointer is declared as (in this case, char
).
因此,在您的示例中,... <<(" + 数字) <<...
等价于 ... <<&<<[数字] <<...
,或更笼统地说:
So, in your example, ... << ("" + number) << ...
is equivalent to ... << &""[number] << ...
, or more generically:
const char *ptr = &""[0];
ptr = reinterpret_cast<const char*>(
reinterpret_cast<const uintptr_t>(ptr)
+ (number * sizeof(char))
);
... << ptr << ...
这意味着当 number
是 0 以外的任何值时,您将超出数组的范围,因此您的代码具有 未定义的行为,并且当 时任何事情都可能发生>operator<<
尝试取消引用你给它的无效指针.
Which means you are going out of bounds of the array when number
is any value other than 0, thus your code has undefined behavior and anything could happen when operator<<
tries to dereference the invalid pointer you give it.
与许多脚本语言不同,("" + number)
不是在 C++ 中将整数转换为字符串的正确方法.您需要改用显式转换函数,例如 std::to_string()
,例如:
Unlike in many scripting languages, ("" + number)
is not the correct way to convert an integer to a string in C++. You need to use an explicit conversion function instead, such as std::to_string()
, eg:
#include <iostream>
#include <string>
int main()
{
long int number = 255;
std::cout << "Value 1 : " << std::flush << std::to_string(number) << std::flush << std::endl;
number = 15155;
std::cout << "Value 2 : " << std::flush << std::to_string(number) << std::flush << std::endl;
return 0;
}
或者,您可以简单地让 std::ostream::operator<<
为您处理该转换,例如:
Or, you can simply let std::ostream::operator<<
handle that conversion for you, eg:
#include <iostream>
int main()
{
long int number = 255;
std::cout<< "Value 1 : " << std::flush << number << std::flush << std::endl;
number = 15155;
std::cout<< "Value 2 : " << std::flush << number << std::flush << std::endl;
return 0;
}
相关文章