在 C 中使用指针进行二维数组操作 [英] 2D array manipulation using a pointer in C
本文介绍了在 C 中使用指针进行二维数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个函数来操作一个二维数组,该函数从主函数接收一个指向二维数组的指针作为其参数.
Let us say I have a function which manipulates a 2D array which receives a pointer to the 2D array from the main function as its parameter.
现在,我想修改(假设每个元素加 10)二维数组的每个元素.
Now, I want to modify(assume add 10 to each element) each element of the 2D array.
我有兴趣了解如何使用给定的单个指针遍历二维数组并返回新修改的数组的指针.
I am interested in knowing about traversing through the 2D array with a single pointer given to me and return the pointer of the newly modified array.
假设指针a
包含二维数组的起始地址.
Assume pointer a
contains the initial address of the 2D array.
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 中使用指针进行二维数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文