打印数组时的垃圾值

Uch*_*chi 0 c++ arrays string new-operator

我使用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;
} 
Run Code Online (Sandbox Code Playgroud)

字符串"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
Run Code Online (Sandbox Code Playgroud)

为什么会这样?而不是其他长度超过12的字符串?

Bar*_*rry 5

您是默认初始化所有ints,实际上并没有为它们分配值.从不确定的值中读取是未定义的行为 - 有时你得到0,有时你得到一些奇怪的值.未定义的行为未定义.

如果你想要全0,你需要对数组进行值初始化:

arr[i] = new int[str.length()]();
//                            ^^
Run Code Online (Sandbox Code Playgroud)

或使用类似memsetstd::fillstd::fill_n.