1

I'm trying to create a dynamic array of arrays. So, for example, let's look at Pascal's Triangle:

1
11
121
1331
14641
...
...

This is basically an array of length N, that has at each index an array of i+1.

How exactly do we set that up?

I've tried a little bit using pointers.

I set up an array of pointers like such:

int *arr[N];

Then I need a pointer i to point to an array of i+1, so I did:

int *i = 0;
    for(int j = 0; j < N; j++){
        int numArr[j+1];
        arr[*i] = numArr;
        *i++;
    }

Am I going the right direction for this? Because I believe I'm supposed to allocate memory for this as I must use free() later. Would I use malloc() for each array initialization?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
ESM
  • 175
  • 10
  • 1
    Yes, you must use `malloc`. If you've never used it before, I suggest you try allocating a single `int`, then once that works perfectly, try allocation an array of `int`, and once *that* works perfectly, take a crack at the problem above. (This is a good approach for any new technique.) – Beta Sep 29 '19 at 19:45
  • 1
    Why bother using a pointer for `i`? Just use `int i` and be done with it. (but yes, you will need to use `malloc` for `numArr`) – S.S. Anne Sep 29 '19 at 20:01

1 Answers1

1

The code could be made extremely simple, if you know what you're doing:

int *arr = malloc(N * sizeof(int*));
int i;
for (i = 0; i < N; ++i) {
    arr[i] = malloc(sizeof(int) * (i + 1));
}

Of course, you'll need corresponding calls to free() further down the line, like this:

for (i = 0; i < N; ++i) {
    free(arr[i]);
}
free(arr);
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • So `free()` would be called when the triangle is complete, and then I just use it once? Or do a for loop and free the memory of each allocated array? – ESM Sep 29 '19 at 22:34
  • You would only call `free()` when you've finished with the arrays. And yes, you would need a `for` loop (see edit). – Adrian Mole Sep 30 '19 at 01:29