2D array manipulation using a pointer in C

 ̄綄美尐妖づ 提交于 2019-12-12 06:38:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!