【问题标题】:Reason for getting garbage values in printing 2-D array through pointer通过指针打印二维数组时获取垃圾值的原因
【发布时间】:2021-10-25 16:14:25
【问题描述】:

我有一个指向动态分配的二维数组的指针,并试图通过取消引用指针来打印数组值。不知何故,一些数组索引显示垃圾值,即使我将它们全部初始化为 1。任何对我做错的洞察力将不胜感激。

int main() {

int (*ptr)[4][4];
int** array;
array = new int*[4];

for (int i = 0; i < 4; i++)
{
    array[i] = new int[4];
}

ptr = (int(*)[4][4])(*array);


for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        array[i][j] = 1;

    }
}

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; ++j)
    {
        cout<<"Val "<<*ptr[i][j]<<" And index "<<i<<" and "<<j<<endl;
    }
}
return 0; }

我的输出:

Val 1 And index 0 and 0
Val 0 And index 0 and 1
Val 1 And index 0 and 2
Val 0 And index 0 and 3
Val 1 And index 1 and 0
Val 0 And index 1 and 1
Val 1 And index 1 and 2
Val 0 And index 1 and 3
Val 543973718 And index 2 and 0
Val 1852383332 And index 2 and 1
Val 10 And index 2 and 2
Val 0 And index 2 and 3
Val 0 And index 3 and 0
Val 0 And index 3 and 1
Val 0 And index 3 and 2
Val 0 And index 3 and 3

【问题讨论】:

  • ptr = (int(*)[4][4])(*array); 你觉得这有什么作用?
  • 你的 C 风格的演员表泄露了它。您将array 分配给ptr,但they are not the same types
  • Tldr:不要使用 C 数组;不要使用明确的new;不要使用拥有原始指针;不要使用 C 强制转换。使用std::vectorstd::array
  • 我认为它使 ptr 指向数组 [0][0]。 我认为它隐藏了编译器会警告您的错误。
  • 它没有。 C 转换隐藏了类型不匹配(基本上它是不兼容的reinterpret_cast),并且ptr 的下一次使用调用未定义行为。

标签: c++ arrays pointers memory data-structures


【解决方案1】:

让我们看看你的基本代码。

int (*ptr)[4][4];
int** array;
array = new int*[4];

for (int i = 0; i < 4; i++)
{
    array[i] = new int[4];
}

ptr = (int(*)[4][4])(*array);

这是最重要的部分。我们来看看什么是数组。

Array 是指向指针的指针。当您以非常 C 风格的方式执行此操作时,您正在执行的操作是可以的。您正在为 4 个指针分配空间,然后每个指针获得 4 个整数的空间。所以这给了你一个 4x4 数组(有点)。

但是ptr 是什么?

int (*ptr)[4][4];

Ptr 是一个指向 4x4 整数数组的指针。那不是数组。数组是一个指向 4 个指针的指针,每个指针指向 4 个整数的空间。它们不一样。

它们的存储方式不同。 Array 共有 5 个指针:自身加上 ​​4 个新指针。

ptr 需要一个指针(本身)指向内存中连续的 16 个整数,没有其他点。

这就是为什么它没有按照您的预期工作。


你也把这弄得太复杂了,但也许是有原因的。 C++ 的方式是显着减少新建/删除的数量。您可以使用 STL 中的容器。

或者你可以这样做:

int array[4][4];

不涉及指针。但也许你希望它是可变的。

【讨论】:

  • 谢谢。这是有道理的。一旦我创建了数组(双指针)指向的动态二维数组,是否有任何正确/可接受的方式让 ptr 指向该数组?
  • @Curiosity 请记住,当您对答案感到满意时,将其中一个标记为最佳。这会将问题标记为已回答,并奖励那些花时间尝试提供帮助的人。
猜你喜欢
  • 1970-01-01
  • 2016-05-14
  • 2014-09-18
  • 2016-05-16
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多