我的程序正在生成4X4矩阵和一个常量项的向量,如下所示:
av + bx + cy + dz = e
a2_v + b2_x + c2_y + d2_z = e_2
a3_v + b3_x + c3_y + d3_z = e_3
a4_v + b4_x + c4_y + d4_z = e_4
在我的generateContentForSystems
方法中,我求解a,b,c,d,a2等的值。
我用g ++编译它,因为我必须在generateContentForSystems
方法中使用C ++库。
虽然它正确地生成了一个包含5个整数的新数组,但它以某种方式将同一个数组分配给myArray[i]
,myArray[i+1]
和myArray[i+2]
。
int arrayIndexes = 0;
int ** myArray = (int **) malloc(1 * sizeof(int));
for (int a = 1; a < 10; a++) {
for (int b = 1; b < 10; b++) {
for (int c = 0; c < 10; c++) {
for (int d = 0; d < 10; d++) {
for(int e = 0; e <10; e++){
myArray[arrayIndexes] = (int *) malloc(5 * sizeof(int));
myArray[arrayIndexes][0] = a;
myArray[arrayIndexes][1] = b;
myArray[arrayIndexes][2] = c;
myArray[arrayIndexes][3] = d;
myArray[arrayIndexes][4] = e;
cout << "a: " << a << "b: " << b << "c: " << c << "d: " << d << "e" << e << endl;
if (arrayIndexes >= 3) {
for (int i = 0; i < arrayIndexes - 2; i++) {
cout << "row: " << myArray[i][0] <<myArray[i][1] << myArray[i][2] << myArray[i][3] << myArray[i][4] << endl;
generateContentForSystems(myArray[arrayIndexes], myArray[i], myArray[i+1], myArray[i+2]);
}
}
++arrayIndexes;
myArray = (int **) realloc(myArray, (arrayIndexes + 1) * sizeof( * myArray));
}
}
}
}
}
这是我运行时的一些输出:
row: 11070
the value of A: 1 1 2 3
1 1 0 7
1 1 0 7
1 1 0 7
row: 11071
the value of A: 1 1 2 3
1 1 0 7
1 1 0 7
1 1 0 7
row: 11072
the value of A: 1 1 2 3
1 1 0 7
1 1 0 7
1 1 0 7
鉴于这是C并且我们正在处理(双)指针,我的预感是我的代码中某处存在一些未定义的行为。你能看出它为什么不保留int指针的值吗?
答案 0 :(得分:2)
在您的代码中
int ** myArray = (int **) malloc(1 * sizeof(int));
非常错误。您正在分配的内存大小等于一个int
的大小,并且在转换后,您将其存储到(as)int *
(s)。除非在平台sizeof (int) == sizeof (int *)
中,否则您将陷入深深的麻烦。
那就是说,你已经为&#34;只有一个&#34;元素,索引更多(从1到9,甚至1本身)到它,如
myArray[arrayIndexes] = .....
在您访问无效内存时调用未定义的行为。