-1

I had recently been for a interview and they had asked me to write a programe to allocate memory dynamically for a two dimensional array (i=3 and j=2)

user123
  • 8,970
  • 2
  • 31
  • 52
Maddy
  • 503
  • 4
  • 12
  • 21

3 Answers3

9
int *a = (int*)malloc(i*j*sizeof(int));

You can get a[k][l] with a[k*i+l];

2

Some of you will hate this, but it is a favorite of mine. The main advantage is that it can be de-allocated through a single free and still allows for access through A[r][c].

#include <stdlib.h>

int main(void)
{
        int num_row = 3, num_col = 2, r;
        int ** A;

        A = malloc(num_row*(sizeof(*A)+num_col*sizeof(**A)));

        for (r = 0; r < num_row; r++)
        {
                A[r] = (int*)(A+num_row)+r*num_col;
        }

        /* Accessing element at row r and column c is through:
         *
         *      A[r][c].
         */

        free(A);

        return 0;
}
Bryan Olivier
  • 5,207
  • 2
  • 16
  • 18
1
int i = 3;
int j = 2;

int** a = malloc(i * sizeof(int*));

for (unsigned int k = 0; k < i; k++) {
    a[k] = malloc(j * sizeof(int));
}

// Now you can use it.
a[0][0] = 0;
a[2][1] = 3;

Haven't you tried searching the SO question database before asking the question?

user123
  • 8,970
  • 2
  • 31
  • 52