【问题标题】:how to set 2d dynamic array with specific values in c++如何在 C++ 中设置具有特定值的二维动态数组
【发布时间】:2015-09-04 21:30:56
【问题描述】:

我创建了一个 2D 动态数组(ary),并将所有元素初始化为 -1 ,,然后我想用一些值设置数组元素,但它不起作用

int rowCount,t;

t=4; rowCount = t/3 + (t % 3 != 0);

int** ary = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    ary[i] = new int[t];


for (int n = 0; n < rowCount*t; n++)
  *((int*)ary + t) = -1;

for(int m=0;m<rowCount;m++)
   for(int h=0;h<t;h++)
ary[m][h]=a[h];  // a is predefined array  

【问题讨论】:

  • 乍一看,您似乎没有初始化rowCount,也没有初始化t。那将是一个表演者。
  • 我初始化它们t=4;rowCount = t/3 + (t % 3 != 0);
  • 为什么初始化不正确?

标签: c++ multidimensional-array dynamic-arrays


【解决方案1】:

如果您仔细分析以下几行,您将意识到您正在越界访问内存并且程序表现出未定义的行为。

for (int n = 0; n < rowCount*t; n++)
  *((int*)ary + t) = -1;

线

  *((int*)ary + t) = -1;

在以下几个方面是错误的。

  1. 您正在将 int** 转换为 int*

  2. 您已经通过多次调用new 分配了内存,但您试图将其视为所有ints 的数据都是通过一次调用new 分配的。

简单的解决方法是:

for (int row = 0; row < rowCount; row++)
{
   for (int col = 0; col < t; ++col )
   {
      arr[row][col] = -1;
   }
}

您还可以选择通过一次调用new 为所有ints 分配内存。在这种情况下,您将不得不担心将行和列映射到其余代码中的一个索引。

// Allocate memory in one chunk.
int* arr = new int[rowCount+t];

// Initialize values to -1.
for (int n = 0; n < rowCount*t; ++n )
{
   arr[n] = -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    相关资源
    最近更新 更多