首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印数组时出现的垃圾值

打印数组时出现的垃圾值
EN

Stack Overflow用户
提问于 2015-10-29 01:56:50
回答 1查看 938关注 0票数 0

我使用new动态声明数组。数组是由字符串长度组成的,这是我从用户那里得到的。当我提供一个长度在7-11之间的字符串时,数组打印的是垃圾值。为什么会发生这种情况?

代码语言:javascript
复制
#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“的输出为:

代码语言:javascript
复制
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的字符串?

EN

回答 1

Stack Overflow用户

发布于 2015-10-29 02:00:33

您正在默认初始化所有的int,这实际上并没有给它们赋值。读取不确定的值是一种未定义的行为--有时你会得到0,有时你会得到一些奇怪的值。未定义的行为未定义。

如果希望全为0,则需要对数组进行值初始化:

代码语言:javascript
复制
arr[i] = new int[str.length()]();
//                            ^^

或者使用诸如memsetstd::fillstd::fill_n之类的东西。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33398267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档