【问题标题】:2D array removes its elements after exiting the loop二维数组在退出循环后删除其元素
【发布时间】:2018-06-29 21:46:43
【问题描述】:

输入是:hello world
以下程序应在 words[0] 中记录“hello”,在 words[1] 中记录“world”

int rowIndex= 0;
char words [100][100];
for (int x = 0 ; x < input.length(); x++)
{
  if (input[x]>='a'&&input[x]<='z' || input[x]>='A'&&input[x]<='Z')
 // This condition is to avoid recording spaces in the array
  {
      words[rowIndex][x]= input[x];
      cout << words[rowIndex][x]<<" ";
  }
  else {
    rowIndex++;
    // Once it finds a space, it records the following characters into the next index
    cout << " Index: " << rowIndex <<endl;
  }
}

输出:
h e l l o
索引:1
w o r l d

cout <<"Index 0: "<< words[0] <<endl;

输出:你好

cout <<"Index 1: "<< words[1] <<endl;

输出:“不输出任何东西”(为什么不输出“世界”)
**************************************************** ******
为什么数组不保存words[1]中的字符而只保存words[0]中的字符
注意:我尝试用动态 2D 数组来做,同样的问题发生了。

【问题讨论】:

  • 你不会在新词上重置x

标签: c++ c++11 visual-c++ c++14


【解决方案1】:

cout &lt;&lt;"Index 1: "&lt;&lt; words[1] 表现出未定义的行为,通过访问从未初始化的 words[1][0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2021-12-18
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    相关资源
    最近更新 更多