我正在使用 new 动态声明数组。该数组由用户提供的字符串长度组成。当我提供长度在 7-11 之间的字符串时,数组正在打印垃圾值。为什么会这样?
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<climits>
#include<vector>
#include<ctime>
#include<map>
using namespace std;
int main(){
string str;
cin>>str;
int i,j;
int** arr = new int*[str.length()];
for(i = 0; i < str.length(); ++i)
arr[i] = new int[str.length()];
for(i=0;i<str.length();i++){
for(j=0;j<str.length();j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
字符串“BBABCBCAB”的输出是:
36397056 0 8 0 -1 0 1111573058 1094926915 0
0 0 4 0 -1 0 1111573058 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
为什么会这样?而不是其他任何长度超过 12 的字符串?
最佳答案
您正在默认初始化所有 int
,这实际上并没有为它们分配一个值。从一个不确定的值中读取是未定义的行为——有时你会得到 0,有时你会得到一些奇怪的值。未定义的行为是未定义的。
如果你想要全0,你需要对数组进行值初始化:
arr[i] = new int[str.length()]();
// ^^
或者使用类似 memset
的东西或 std::fill
或 std::fill_n
.
关于c++ - 打印数组时的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33398267/