我在C中创建了一个二维整数数组,用值初始化它,然后将它转换为int**
(我必须这样做,因为它是用于作业)。
我已经设法迭代它并将所有值设置为0.但是,当我再次遍历它并打印它的值时,输出不是全零。
这是一个最小的工作示例:
#include <string.h>
#include <stdio.h>
#define ROWS 3
#define COLS 2
int main(void)
{
/* Create array and convert to double pointer */
int c[ROWS][COLS] = {{1,2},{3,5},{8,13}};
int **ptr = (int **)c;
/* Loop through entire array and print then double each value. */
int *temp[ROWS];
for(int i = 0; i<ROWS; i++){
temp[i] = (int*)(ptr+i);
for(int j = 0; j<COLS; j++){
printf("Before setting: %i\n", temp[i][j]);
temp[i][j] = temp[i][j]*2;
}
}
/* Copy temp back into ptr */
memcpy(ptr, temp, sizeof(ptr));
/* Loop through array and print values */
int *temp2[ROWS];
for(int i = 0; i<ROWS; i++){
temp2[i] = (int*)(ptr+i);
for(int j = 0; j<COLS; j++){
printf("After setting: %i\n", temp2[i][j]);
}
}
}
问题是结果不是我所期望的。有一次我跑了,这是输出:
在设置之前:1 在设置之前:2 设定前:3 设置前:5 设定前:8 在设置之前:13 设置后:-1193330832 设置后:32764 设定后:6 设定后:10 设定后:16 设定后:26
每次运行程序时,值32764
都是相同的,但值-1193330832
每次都会改变(我假设它是数组的内存地址)。
我期待的输出是:
在设置之前:1 在设置之前:2 设定前:3 设置前:5 设定前:8 在设置之前:13 设定后:1 设定后:4 设定后:6 设定后:10 设定后:16 设定后:26 因为第一个循环中的值加倍了。
我做错了什么?为什么价值观会发生变化,我该如何解决这个问题呢?
(P.S.家庭作业不涉及找到迭代双指针的方法,但我需要能够完成实际任务)
int **ptr = (int **)c;
不是有效的指针转换,因为您不能使用指向指针的指针指向2D数组。因为它与2D数组无关。
相反,你可以使用指向二维数组的指针int (*)[ROWS][COLS];
。然而,最方便的是使用指向1D数组的指针并使其指向2D数组的第一个元素:
int (*ptr)[COLS] = &c[0];
...
ptr[i][j] = ...;
固定示例:
#include <string.h>
#include <stdio.h>
#define ROWS 3
#define COLS 2
int main(void)
{
/* Create array and convert to double pointer */
int c[ROWS][COLS] = {{1,2},{3,5},{8,13}};
int (*ptr)[COLS] = &c[0];
/* Loop through entire array and print then double each value. */
for(int i = 0; i<ROWS; i++){
for(int j = 0; j<COLS; j++){
printf("Before setting: %i\n", ptr[i][j]);
ptr[i][j] = ptr[i][j]*2;
}
}
/* Loop through array and print values */
for(int i = 0; i<ROWS; i++){
for(int j = 0; j<COLS; j++){
printf("After setting: %i\n", ptr[i][j]);
}
}
}
(关于风格,但你的ROWS和COLS的顺序有点奇怪,更常见的是做int[COLS][ROWS]
然后for(i=0; i<COLS; i++)
)