问题
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.
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.
Rough Structure
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];
}
回答1:
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;
}
来源:https://stackoverflow.com/questions/7949008/2d-array-manipulation-using-a-pointer-in-c