Cout我的动态数组时获取垃圾值 [英] Getting rubbish value when cout my dynamic array

查看:37
本文介绍了Cout我的动态数组时获取垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的程序的一个片段

Below is a snippet of my program

主要功能

int main()
{
    ...

    int x_length = 0;
    int * mapX = new[x_length];
    functionA(x_length, mapX);

    ...
    delete[]mapX;
}

功能A

void functionA(int &x_length, int *&mapX)
{
    ...
    int x_pos = 0;
    int x_length_functionA = 0; // declare internal variable

    ...

    for(int i=0; i <= 8; i++)
    {
        ++x_length_functionA;
    }

    int * mapX_functionA = new int[x_length_functionA];

    for(int i = 0; i < x_length_functionA; i++)
    {
        mapX_functionA[x_pos++] = i;
    }

    x_length = x_length_functionA; // x_length_functionA is 9
    mapX = mapX_functionA;
    
    ...
    delete[]mapX_functionA;
}

当我 functionA 内的 mapX_functionA 数组时,该数组输出是正确的,即:

When I cout the mapX_functionA array inside functionA, the array output is correct that is:

更正函数A中的提示

0
1
2
3
4
5
6
7
8

当我在 mapX 上的主函数中退出时,我得到一些垃圾第一值,即

When I cout in my main function on mapX, I get some rubbish first value that is

主要功能中的提示不正确

157306016 // this is suppose to be 0!
1
2
3
4
5
6
7
8

我非常确定这可能是由于某处的内存故障所致.

I am quite sure this could be due to memory fault somewhere.

我以为我做对了一切-函数声明中通过引用传递了 mapX ,然后将 mapX_functionA 复制到了 mapX 将工作.当我在 main 中检查 x_length 时,它会输出正确的整数.

I thought I have did everything right - the mapX is pass by reference in the function declaration, and I copy the mapX_functionA to mapX will work. When I check x_length in main, it output the correct integer.

为什么第一个数组获得此垃圾值?

Why is the first array getting this rubbish value?

P.S:在有人问我为什么不使用向量之前,这是出于教育和知识目的.

P.S: Before anyone ask why I didn't use vector, this is for educational and knowledge purpose.

推荐答案

mapX = mapX_functionA;

在此行上,使 mapX 指向与 mapX_functionA 相同的数组.

On this line, you make mapX point to same array as mapX_functionA.

delete[]mapX_functionA;

在此行上,删除 mapX_functionA mapX 指向的数组.所有指向数组的指针都将变为无效.

On this line, you delete the array pointed by mapX_functionA and mapX. All pointers to the array become invalid.

主要功能中的提示不正确

Incorrect cout in main function

您无法显示所打印的内容,但是我假设您是通过 mapX 间接执行的,现在这是无效的,因此程序的行为是不确定的.

You failed to show what you are printing, but it is my assumption that you indirect through mapX which is now invalid, and therefore the behaviour of your program is undefined.

您还稍后在 main 的最后一行删除此无效指针:

You also later delete this invalid pointer on the last line of main:

delete[]mapX;

还有哪些不确定的行为.

Which also has undefined behaviour.

P.S.您泄漏了您在这一行所做的分配:

P.S. You leak the allocation that you make on this line:

int * mapX = new[x_length];

因为指针值在行上被覆盖

because that pointer value is overwritten on line

mapX = mapX_functionA;

您也未能声明您在在线上分配的变量:

You also failed to declare the variable that you assign on line:

x_length_functionA = 0;

这篇关于Cout我的动态数组时获取垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆