-1

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];
}
2
  • 1
    Try searching "2d array c" on stack overflow. You might find a few answers. Commented Oct 31, 2011 at 0:48
  • It depends on whether you have pointer to an array (int (*a)[N])), or a pointer to a pointer to int (int**); you'll have to declare your function accordingly. The syntax a[i][j] is the same in both cases, though. Commented Oct 31, 2011 at 0:50

1 Answer 1

0
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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

This breaks if he's using 2d arrays, or pointer-to-array types, rather than an array of arrays.
@Dave ...Is *(*(dest + i) + j) = 10 + *(*(source + i) + j); better? I would have thought both versions were correct.
No, you're using a fundamentally different type. int k[5][5] is a contiguous block of 25 ints. It it not an array of arrays.
There is no function that would be guaranteed to work for both; but the op asked about 2d arrays.
@Dave So... Is this better? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.