#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
char a[10]="Rosewater";
char b[3];
int i=0;
for(i=0;i<5;i++)
{
b[i]=a[i]; //1. does not throw an error
}
printf("%s\n%s\n",a,b);
}
输出:
ewsewater // value of a also changed
Rosewsewater // unclear output
最佳答案
//1. does not throw an error
在C和C++中没有边界检查,因为它只是暴露原始内存。
这被定义为未定义行为。 这意味着(很简单)标准没有指定程序中会发生什么,当指令产生未定义的行为时,任何事情都可能发生。
如果您使用C(这是与C不同的语言),我的建议是使用std::vector
类。 Here References .
请注意,当您尝试访问越界索引时,std::vector
会产生未定义的行为。方法at
,相反,在这种情况下会抛出异常。
#include <vector>
int main(int argc, char* argv[]) {
std::vector<char> a = {'a', 'b', 'c'};
a.at(5); // it will throw an exception
return 0;
}
此外,如果您必须管理字符串,最方便的类是 std::string
.
关于c++ - 字符串的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556762/