首页 > 解决方案 > 当数组(句子)只有 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++ 很陌生,所以我不确定这是语言本身的问题还是我自己的问题。任何帮助表示赞赏。

标签: c++arraysc-strings

解决方案


使用大于数组大小的索引对数组进行索引是未定义的操作。你永远不会知道输出会是什么。例如,在您的情况下,如果您尝试访问 char c = sentence[37],这是未定义的操作。意味着 char c 可以是从句子的内存位置读取的任何内容 + 37 * sizeof(char) (第 37 个元素的地址)。我的建议是使用向量,并在索引时使用 at() 方法。如果您尝试访问为该向量保留的空间之外的元素,方法 at() 将抛出 out_of_range 异常。


推荐阅读