-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];
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
c_prog_90
  • 951
  • 20
  • 43
  • 1
    Try searching "2d array c" on stack overflow. You *might* find a few answers. – Brian Roach Oct 31 '11 at 00: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. – Kerrek SB Oct 31 '11 at 00:50

1 Answers1

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;
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • This breaks if he's using 2d arrays, or pointer-to-array types, rather than an array of arrays. – Dave Oct 31 '11 at 02:33
  • @Dave ...Is `*(*(dest + i) + j) = 10 + *(*(source + i) + j);` better? I would have thought both versions were correct. – Mateen Ulhaq Oct 31 '11 at 03:06
  • 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. – Dave Oct 31 '11 at 03:11
  • There is no function that would be guaranteed to work for both; but the op asked about 2d arrays. – Dave Oct 31 '11 at 03:14
  • @Dave So... Is this better? :) – Mateen Ulhaq Oct 31 '11 at 03:26
  • Yes, it is. I might use `memcpy()` rather than `memmove()`, though. – Dave Oct 31 '11 at 03:46
  • @Dave: A 2-d array *is* precisely an array of arrays. `int k[5][5]` makes `k` an array of 5 elements, each of which is an array of 5 ints; that's what a 2-d array is in C. – Keith Thompson Oct 31 '11 at 04:25