c++ - 当数组(句子)只有 30 个空间时,为什么要打印 38 个元素?
问题描述
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
int main() {
//initialising the char array and vector
char sentence[30] = {};
vector<string> words{"The", "only", "thing", "to", "fear", "is", "fear", "itself"};
//For loop iterates through the vector and adds the converted strings to the char array
for(int i = 0; i < words.size(); i++){
//if statements check if there is overflow and breaks the loop if there is
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds the strings from words to sentence one at a time
strcat(sentence, words[i].c_str());
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds a space in between each word in the cstring
strcat(sentence, " ");
}
//couts the full sentence and the length of sentence
cout << sentence << " " << strlen(sentence) << endl;
cout << sentence[29] << endl;
return 0;
}
我注释掉了如果数组超过 30 个元素但现在返回 38 时中断的 if 语句。当我尝试访问数组可以容纳的元素以上时,它仍然给我一个错误。一旦数组goa中的元素数量超过30,编译器不应该抛出错误吗?我对 C++ 很陌生,所以我不确定这是语言本身的问题还是我自己的问题。任何帮助表示赞赏。
解决方案
使用大于数组大小的索引对数组进行索引是未定义的操作。你永远不会知道输出会是什么。例如,在您的情况下,如果您尝试访问 char c = sentence[37],这是未定义的操作。意味着 char c 可以是从句子的内存位置读取的任何内容 + 37 * sizeof(char) (第 37 个元素的地址)。我的建议是使用向量,并在索引时使用 at() 方法。如果您尝试访问为该向量保留的空间之外的元素,方法 at() 将抛出 out_of_range 异常。
推荐阅读
- javascript - 在我的情况下,通过 JavaScript 从 EntityFramework 数据库获取数据的最佳和最有效的方法是什么?
- vba - Add printer to system using Powershell within VBA?
- python - 如果它们为 None,则调用不带可选参数的函数
- excel - 计算行并进行最大排列
- c++ - 动态链接如何对对象的变化作出反应
- amcharts - 如何在amcharts的更新图表中添加amgraph
- spring-boot - 无法从 Spring Boots 1.4 更新到 1.5.10
- javascript - HTML5 数据列表:仅在单击箭头时显示下拉列表
- google-apps-script - 如果工作表被另外修改,则 IMPORTRANGE 值将变为错误
- twilio - Twillio 使用自定义号码通知批量短信