c++ - 打印数组时的垃圾值

标签 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;
} 

字符串“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::fillstd::fill_n .

关于c++ - 打印数组时的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33398267/

相关文章:

javascript - 在元素连续出现后获取 JavaScript 数组元素

电子邮件数组上的 PHP OOP 过滤器验证

javascript - 将数组转换为新数组(计算出现次数)

c++ - 如何正确重写 ASSERT 代码以在 msvc 中传递/分析?

c++ - 我的 Hook 不起作用

c++ - 如何使用标准 STL 算法从 istream 填充 std::vector

r - 将字符串矩阵拆分为R中的数字矩阵

c++ - C++中的指针变量只指向堆中的变量?

string - Rust 枚举中 str/String 值的最佳实践是什么?

从字符串中切割 '\0'