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?

2
  • 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.) Commented Sep 29, 2019 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) Commented Sep 29, 2019 at 20:01

1 Answer 1

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

2 Comments

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?
You would only call free() when you've finished with the arrays. And yes, you would need a for loop (see edit).

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.