我使用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的字符串?
发布于 2015-10-29 02:00:33
您正在默认初始化所有的int,这实际上并没有给它们赋值。读取不确定的值是一种未定义的行为--有时你会得到0,有时你会得到一些奇怪的值。未定义的行为未定义。
如果希望全为0,则需要对数组进行值初始化:
arr[i] = new int[str.length()]();
// ^^或者使用诸如memset、std::fill或std::fill_n之类的东西。
https://stackoverflow.com/questions/33398267
复制相似问题