How to use a single malloc() call for a 2D array

1

I want to malloc a large block of memory then access it as a 2D array.

The malloc call is pretty strait forward, something like this.

const int rows = 1000;
const int cols = 2048;
uint32_t* mal_ptr = malloc(sizeof(uint32_t)*rows*cols);

After that I don't know how to declare a pointer that I can use to access this block of memory as a 2D array. I don't want to call malloc in a loop because I know the size of the whole array up front.

Can I do something like this?

uint32_t big_array[][cols];
big_array = mal_ptr;
for(int row=0; row<rows; row++) {
    for(int col=0; col<cols; col++) {
        big_array[row][col] = (uint32_t)(0xdeadbeef);
    }
}
c
arrays
malloc
asked on Stack Overflow May 3, 2018 by Pedro_Uno

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0