# Dynamically allocate 2D array of ints

• 10-24-2009
steals10304
Dynamically allocate 2D array of ints
In this problem, I am required to allocate memory ALL AT ONCE. Only one dynamic allocation is allowed. I believe I have code that will allocate all memory needed:

Code:

``` int ** p; int cols, rows; p = (int **)malloc(((rows * sizeof(int *)) + (cols * rows * sizeof(int)))```
cols and rows are passed in as arguments, (let's assume cols = 4, rows = 3). So now I have one big block of memory that will hold 3 pointers to ints which point to the first int in 3 rows of four ints. P will point to my first pointer to int.

I am having a hard time understanding how to initialize the pointers to ints logically. I believe a looping function is needed. Any advice?
• 10-24-2009
tabstop
Why go to all that trouble? Are you required to access the element using [two][subscripts]? Why not just allocate memory the way C would, by getting one big block that holds row*col entries?
• 10-24-2009
steals10304
Yes, forgive me for my noobness (if that's not a word, I just coined it), but shouldn't you be able to access any 2 Dimensional pointer array with [two][subscript] notation?

One requirement of this ASSIGNMENT is that we must only call for one block of memory. Also it will contain a pointer array that points to int arrays, as described in my initial posting.
• 10-24-2009
tabstop
That dual requirement is unfortunate since it makes things about 276 times more complicated than it really needs to be.

In that case your malloc looks correct. You will then need to initialize your "first dimension" by setting all the pointers to point to the correct places in memory. p[0] should be assigned the start of the "data" portion of the memory (you'll have to get there with pointer arithmetic), then p[1] needs to be assigned the start of the next row (pointer arithmetic), then p[2] the start of the row after that (pointer arithmetic) and so on.