【问题标题】:How to make it show the actual value of the array, not the pointer value ( actually don't really know what means "-8589934604") [duplicate]如何让它显示数组的实际值,而不是指针值(实际上并不知道“-8589934604”是什么意思)[重复]
【发布时间】:2021-07-22 05:13:11
【问题描述】:

// 我实在想不通这段代码有什么问题,而且我无法得到初始数组值为零。

#include <iostream>
int* create()

{
    int arr[5] = { 0,0,0,0,0 };
    return arr;
}
void disp(int arr[])
{
        for (int j = 0; j < 5; j++)
        {
            std::cout << arr[j];
        }
        std::cout << std::endl;
}


int main()
{
    int* mat = create();
    std::cout << mat[2] << std::endl;
    disp(mat);
}
//what it displays:
0
-858993460-858993460-858993460-8589934604

【问题讨论】:

  • 常规数字转换为十六进制为 FFFFFFFDFFFFFFF4。你认得出来吗?
  • arr 是函数本地的,返回它是个坏主意,一旦函数返回,它的生命周期就结束了。
  • 另一种方法是将create 中的数组声明为staticstatic 关键字将确保数组在执行离开函数后不会消失。

标签: c++ arrays


【解决方案1】:

您的代码无法为我运行。我收到警告“返回局部变量‘arr’的地址”。当你使用这样的数组引用时,你应该使用动态数组来避免这些类型的错误。我相应地更改了 arr 并且它有效。

int* create()
{
    int * arr = new int[5] {0,0,0,0,0};
    return arr;
}

但是,现在 arr 在不再使用时不会被破坏。如果您一遍又一遍地调用此创建函数,您应该创建自己的具有适当析构函数的容器,或者使用标准库提供的现代容器之一(std::vector、std::array)。

【讨论】:

  • Aaaaa 然后你有内存泄漏......不要在现代 C++ 中使用原始指针。在这种情况下,要么使用(并返回)std::array 要么 std::vector
  • 你会推荐什么替代品?
  • @JHBonarius 完全同意,只是想在不改变原文的情况下回答
猜你喜欢
  • 2012-02-09
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2020-02-15
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多