我正在解决一个调度问题,并且正在创建一个实例生成器。 我有一个问题——数组 t1、t2、t3 指向相同的存储单元,因此所有数组在分配后都具有相同的数据。 这是我的代码
(...)
int **t1;
t1= new int*[1];
t1[1]=new int[2];
int **t2;
t2= new int*[1];
t2[1]=new int[2];
int **t3;
t3= new int*[1];
t3[1]=new int[2];
for (int s=0; s<20; s++ )
{
for (int w=0; w<3; w++)
{
time[w]=(rand() % 200) +1;
machine[w]= (rand() % 3) +1;
if (w>0)
while (machine[w]==machine[w-1] || machine[w]==machine[0])
{
machine[w]= (rand() % 3) +1;
}
}
t1[0][0]=machine[0];
t1[0][1]=time[0];
t2[0][0]=machine[1];
t2[0][1]=time[1];
t3[0][0]=machine[2];
t3[0][1]=time[2];
(...)
非常感谢!
最佳答案
t1= new int*[1];
分配一个指针数组。
t1[1]=new int[2];
写入这个单元素数组的第二个元素。这会导致未定义的行为。在你的情况下,这听起来像 &t1==&t2[1]
,导致您每次创建新数组时都覆盖先前分配的地址。
您应该写入数组的第一个元素
t1[0]=new int[2];
// ^
如果使用 C 风格的数组不是赋值的要求,您可以实现 int
的数组。使用 std::vector<int>
更容易.
关于c++ - 2个不同的数组,一个分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311769/