【发布时间】:2020-02-19 21:09:26
【问题描述】:
我是 C++ 新手,我试图弄清楚如何获取一个名为 temp 的 2D 动态数组,以从另一个名为 array 的 2D 动态数组中获取值。我不知道如何将数组中的任何值分配给 temp,因为语句 'temp[0][0] = array[0][0];'似乎没有将 array[0][0] 的值为 1 分配给 temp[0][0]。相反,在将任何值分配给 temp[0][0] 之前,在“temp[0][0] = array[0][0]”之后,temp[0][0] 似乎具有相同的随机数。我试图将 temp[0][0] 分配给 2 并且它有效。我真的不知道如何将一个二维动态数组中的值准确地分配给另一个。无论如何,提前感谢您帮助我!
...
//initializing first 2D dynamic array
int x=2;
int y=2;
int** array = new int*[x];
for(int i=0; i<x; i++) array[i] = new int[y];
//initializing second 2D dynamic array
int new_x=3;
int new_y=3;
int** temp = new int*[new_x];
for(int i=0; i<new_x; i++) temp[i] = new int[new_y];
//assigning values
array[0][0] = 1;
cout << array[0][0] << endl; //output is 1
//before assigning values to temp[0][0]
cout << temp[0][0] << endl; //out is a huge random number
temp[0][0] = array[0][0];
cout << temp[0][0] << endl; //output is the same huge random number
temp[0][0] = 2;
cout << temp[0][0] << endl; //output is 2
...
【问题讨论】:
-
请提供一个演示问题的最小完整程序。使用您的代码无法重现错误。
-
去掉
...并发布一个复制错误的真实代码示例。这意味着所有#include和int main()等等。 -
编译并运行它。分配
temp[0][0] = array[0][0];在我的程序中按预期工作。也许你周围的东西...是问题所在。借用上述 cmets 所说的:编写一个可以编译和运行的自包含程序以验证问题是否存在,然后给我们确切的代码。#includes 和所有。 -
谢谢,我差点冲到编译器来检查这个奇迹。但是没有奇迹:)
-
这两个数组的大小不同,你确定你看到的奇怪输出是关于第一个元素而不是其他一些未确定的值吗?
标签: c++ dynamic-arrays assign