Search code examples
cpointersdouble-pointerpascals-triangle

Creating a dynamic array of arrays using pointers


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?


Solution

  • 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);