指针到指针算术:赋值

Pointer-to-Pointer Arithmetic: Assigning Values

本文关键字:指针 赋值      更新时间:2023-10-16

我的程序正在生成 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 指针的值吗?

在你的代码中

int ** myArray = (int **) malloc(1 * sizeof(int));

大错特错。您正在分配等于一个int大小的内存,并且在转换后,您将其存储为(作为(int *(s(。除非在平台中,sizeof (int) == sizeof (int *),否则您将陷入深深的麻烦。

也就是说,您已经为"只有一个"元素分配了空间,将更多索引(从 1 到 9,甚至 1 本身(放入其中,例如

myArray[arrayIndexes] = .....

调用未定义的行为,因为您正在访问无效内存。