假设我有一个操作 2D 数组的函数,该函数从主函数接收指向 2D 数组的指针作为其参数。
现在,我想修改(假设每个元素加 10)二维数组的每个元素。
我有兴趣了解如何使用给我的单个指针遍历二维数组并返回新修改的数组的指针。
粗略结构
假设指针a
包含二维数组的初始地址。
int add_10(int *a)
{
int i, j,
b[M][N] = {0};
for(i = 0; i < M; i++)
for(j = 0; j < N; j++)
b[i][j] = 10 + a[i][j];
}
最佳答案
int* add_10(const int *dest,
const int *src,
const int M,
const int N)
{
int *idest = dest;
memmove(dest, src, M * N * sizeof(int));
for(int i = 0; i < (M * N); ++i)
*idest++ += 10;
return dest;
}
关于c - 在 C 中使用指针操作二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7949008/