How do we allocate a 2-D array using One malloc statement

I have been asked in an interview how do i allocate a 2-D array and below was my solution to it.

#include <stdlib.h>

    int **array;
    array = malloc(nrows * sizeof(int *));

    for(i = 0; i < nrows; i++)
        {
        array[i] = malloc(ncolumns * sizeof(int));
        if(array[i] == NULL)
            {
            fprintf(stderr, "out of memory/n");
            exit or return
            }
        }

I thought I have done good job but then he asked me to do it using one malloc statement not two.I don’t have any idea how to achieve it.

Can anyone suggest me some idea to do it in single malloc?

How does C allocate space for a 2D (3Dā€¦) array when using malloc?

I am having a problem understanding how C allocates space for a 2D (or more dimensional) array, especially when we use malloc and the like. Take the program in this question for example. A one-dimensi

Dynamically allocate 2D array without using any loops?

Can we dynamically allocate 2D array without using any for loop or while loops? i there any direct command or function in c c++?

Allocate memory for 2D array with minimum number of malloc calls

I am using the below code snippet to allocate memory for 2D array using minimum number of malloc() calls. I want to access the array using subscripts, p[i][j]. #define ROW 3 #define COL 2 int main() {

Allocating memory for 2d matrix using 1 malloc call

We can allocate memory for 2d matrix using 1 malloc call as int (*a)[5]; int i,j; a=malloc(sizeof(int*) * 5); //allocating 5 pointers and each pointer points to an array of 5 ints How can we free thi

How to dynamically allocate 2d array that’s 16B aligned

I’d like to allocate 2d array (square matrix) using memalign with 16B instead of using just malloc. I have A =(float **) malloc( (*dim) * sizeof(float*)); for ( i = 0 ; i < (*dim) ; i++) { A[i] = (

How to dynamically allocate a contiguous block of memory for a 2D array

If I allocate a 2D array like this int a[N][N]; it will allocate a contiguous block of memory. But if I try to do it dynamically like this : int **a = malloc(rows * sizeof(int*)); for(int i = 0; i &l

How to allocate memory using this malloc statement?

I have this method that reads a file. A matrix to be more specific where the first two numbers are the rows and the columns. However when i try to allocate the memory using malloc and using the rows a

Allocate a 2d array in C with one dimension fixed

I want to dynamically allocate 1 dimension of a 2D array (the other dimension is given). Does this work: int NCOLS = 20; // nrows = user input… double *arr[NCOLS]; arr = (double *)malloc(sizeof(doub

Assigning values to 2D array created using malloc

I created a 2D character array using malloc and have been trying to assign its values to ‘/0’. char **predicate_array = malloc(no_of_lines_in_data_map); for(int i = 0; i < no_of_lines_in_data_map;

how to define a 2d array using malloc and pass it to a function

I want to pass a 2d array i defined using malloc to a function. First i define the array using code from a blog post. int** Make2DIntArray(int arraySizeX, int arraySizeY) { int** theArray; theArray =

Answers

int **array = malloc (nrows * sizeof(int *) + (nrows * (ncolumns * sizeof(int)));

This works because in C, arrays are just all the elements one after another as a bunch of bytes. There is no metadata or anything. malloc() does not know whether it is allocating for use as chars, ints or lines in an array.

Then, you have to initialize:

int *offs = &array[nrows]; /*  same as int *offs = array + nrows; */
for (i = 0; i < nrows; i++, offs += ncolumns) {
    array[i] = offs;
}

You should be able to do this with (bit ugly with all the casting though):

int** array;
size_t pitch, ptrs, i;   
char* base; 
pitch = rows * sizeof(int);
ptrs = sizeof(int*) * rows;
array = (int**)malloc((columns * pitch) + ptrs);
base = (char*)array + ptrs;
for(i = 0; i < rows; i++)
{
    array[i] = (int*)(base + (pitch * i));
}

Just compute the total amount of memory needed for both nrows row-pointers, and the actual data, add it all up, and do a single call:

int **array = malloc(nrows * sizeof *array + (nrows * (ncolumns * sizeof **array));

If you think this looks too complex, you can split it up and make it a bit self-documenting by naming the different terms of the size expression:

int **array; /* Declare this first so we can use it with sizeof. */
const size_t row_pointers_bytes = nrows * sizeof *array;
const size_t row_elements_bytes = ncolumns * sizeof **array;
array = malloc(row_pointers_bytes + nrows * row_elements_bytes);

You then need to go through and initialize the row pointers so that each row’s pointer points at the first element for that particular row:

size_t i;
int *data = array + nrows;
for(i = 0; i < nrows; i++)
  array[i] = data + i * ncolumns;

Note that the resulting structure is subtly different from what you get if you do e.g. int array[nrows][ncolumns], because we have explicit row pointers, meaning that for an array allocated like this, there’s no real requirement that all rows have the same number of columns.

Here’s another approach.

If you know the number of columns at compile time, you can do something like this:

#define COLS ... // integer value > 0
...
size_t rows;
int (*arr)[COLS];
...              // get number of rows
arr = malloc(sizeof *arr * rows);
if (arr)
{
  size_t i, j;
  for (i = 0; i < rows; i++)
    for (j = 0; j < COLS; j++)
      arr[i][j] = ...;
}

If you’re working in C99, you can use a pointer to a VLA:

size_t rows, cols;
...               // get rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
  size_t i, j;
  for (i = 0; i < rows; i++)
    for (j = 0; j < cols; j++)
      arr[i][j] = ...;
}

I’m not a fan of this “array of pointers to array” to solve the multi dimension array paradigm. Always favored a single dimension array, at access the element with array[ row * cols + col]? No problems encapsulating everything in a class, and implementing a ‘at’ method.

If you insist on accessing the members of the array with this notation: Matrix[i][j], you can do a little C++ magic. @John solution tries to do it this way, but he requires the number of column to be known at compile time. With some C++ and overriding the operator[], you can get this completely:

class Row
{
private:
    int* _p;

public:
    Row( int* p )                   { _p = p; }
    int& operator[](int col)        { return _p[col]; }
};


class Matrix
{
private:
    int* _p;
    int _cols;

public:
    Matrix( int rows, int cols )  { _cols=cols; _p = (int*)malloc(rows*cols ); }
    Row operator[](int row)       { return _p + row*_cols; }
};

So now, you can use the Matrix object, for example to create a multiplication table:

Matrix mtrx(rows, cols);
for( i=0; i<rows; ++i ) {
    for( j=0; j<rows; ++j ) {
        mtrx[i][j] = i*j;
    }
}

You should now that the optimizer is doing the right thing and there is no call function or any other kind of overhead. No constructor is called. As long as you don’t move the Matrix between function, even the _cols variable isn’t created. The statement mtrx[i][j] basically does mtrx[i*cols+j].