Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 had done a 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()?

like image 517
Amit Singh Tomar Avatar asked Jan 05 '12 09:01

Amit Singh Tomar


People also ask

How do I malloc a 2D array?

Dynamically Allocated 2D Arrays Make multiple calls to malloc , allocating an array of arrays. First, allocate a 1D array of N pointers to the element type, with a 1D array of pointers for each row in the 2D array. Then, allocate N 1D arrays of size M to store the set of column values for each row in the 2D array.

How do you declare an array in malloc?

Let A be an integer pointer (declared int *A). To get the array, use the command: A = (int *) malloc( 10 * sizeof(int) ); The sizeof() function is expanded by the compiler to be the number of bytes in one element of the type given as the argument.


5 Answers

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 * const 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.

It also means that an access like array[2][3] does something distinct from a similar-looking access into an actual 2d array. In this case, the innermost access happens first, and array[2] reads out a pointer from the 3rd element in array. That pointer is then treatet as the base of a (column) array, into which we index to get the fourth element.

In contrast, for something like

int array2[4][3]; 

which is a "packed" proper 2d array taking up just 12 integers' worth of space, an access like array[3][2] simply breaks down to adding an offset to the base address to get at the element.

like image 170
unwind Avatar answered Sep 29 '22 22:09

unwind


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; } 
like image 24
Prof. Falken Avatar answered Sep 29 '22 23:09

Prof. Falken


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] = ...;
}
like image 45
John Bode Avatar answered Sep 29 '22 23:09

John Bode


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

No answers, so far, allocate memory for a true 2D array.

int **array is a pointer to pointer to int. array is not a pointer to a 2D array.

int a[2][3] is an example of a true 2D array or array 2 of array 3 of int


To allocate memory for a true 2D array, with C99, use malloc() and save to a pointer to a variable-length array (VLA)

// Simply allocate and initialize in one line of code
int (*c)[nrows][ncolumns] = malloc(sizeof *c);

if (c == NULL) {
  fprintf(stderr, "out of memory\n");
  return;
} 
// Use c
(*c)[1][2] = rand();
...
free(c);

Without VLA support, if the dimensions are constants, code can use

#define NROW 4
#define NCOL 5
int (*d)[NROW][NCOL] = malloc(sizeof *d);
like image 23
chux - Reinstate Monica Avatar answered Sep 29 '22 23:09

chux - Reinstate Monica


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));
}
like image 44
Necrolis Avatar answered Sep 29 '22 23:09

Necrolis