1

For each time step, I have a 2D matrix a[ix][iz] with ix varying from 0 to nx-1 and iz varying from 0 to nz-1.

To assemble the matrix of all the time steps, I define a 3D pointer ***b of length nx*nz*nt. At time it the matrix can be represented by b[ix][iz][it] with ix varying from 0 to nx-1 and iz varying from 0 to nz-1.

In the time loop, I have to deliver the 2D array/pointer at time it to the function void func(**ptr). Because b is a 3D pointer/array, how can I call it in the main code? Like func(b[it]);?

2 Answers 2

3

You could restructure your matrix as b[it][ix][iz] instead of b[ix][iz][it]. This way, you'd have an array of 2D matrices, allowing you to pass in the 2D matrix at any given timestep using b[it].

Otherwise, if you keep your matrix as-is, you'd have to construct the 2D array at time it, then pass that into func() - that's extra computation that you can avoid by restructuring your 3D matrix.

Sign up to request clarification or add additional context in comments.

Comments

3

The simplest way would be to use your b to just store pointers to matrices like this:

In each timestep, copy your matrix a and insert the pointer to the copy of matrix a into b. Then, you can pass b[i] over to your function func(b[i]) .

That is basically what frsim suggests as well. In code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX_TIME 5

void func(int array[2][3]) {

    for(size_t x = 0; x < 2; ++x) {

        for(size_t y = 0; y < 3; ++y) {
            printf("%i ", array[x][y]);
        }
        printf("\n");

    }
    printf("\n");

}

int main (int argc, char** argv) {

   int a[2][3] = {{1, 2, 3}, {4, 5, 6}};

   int b[MAX_TIME][2][3] = {0};

   for(size_t time = 0; time < MAX_TIME; ++time) {

       /* Calculate your new version of `a` here */

       a[1][0] = time;

       memcpy(b[time], a, sizeof(a));
       printf("%zu ", sizeof(a));

   }

   for(size_t i = 0; i < MAX_TIME; ++i) {
       printf("time: %zu \n", i);
       func(b[i]);
   }

}

Arrays bear a lot of pitfalls, in particular, an array is not a pointer.

But: If you pass an array to a function, what happens is that not the array itself will be passed into the function, but a pointer to the array. The same would happen with a two-dimensional array: When calling a function with a two-dimensional array, what is passed into the function is not the array, but a pointer, and this pointer is still just int * and not int **... See e.g. this question

1 Comment

"but a pointer to the array" --> "but a pointer to the first element of the array".

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.