Saturday, December 5, 2009

C code to dynamically allocate one, two and three dimensional arrays (using malloc())

One Dimensional Array
int *myarray = malloc(no_of_elements * sizeof(int));

//Access elements as myarray[i]

2 Dimensional Array
Method1
int **myarray = (int **)malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
 myarray[i] = malloc(ncolumns * sizeof(int));
//allocating 1 D array = number of elements in column
}

// Access elements as myarray[i][j]

Method 2 (Contagious Allocation)
int **myarray = (int **)malloc(nrows * sizeof(int *));
myarray[0] = malloc(nrows * ncolumns * sizeof(int));

for(i = 1; i < no_of_rows; i++)
  myarray[i] = myarray[0] + (i * ncolumns);

// Access elements as myarray[i][j]

In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]

Method 3
int *myarray = malloc(nrows * ncolumns * sizeof(int));

// Access elements using myarray[i * ncolumns + j].
i.e. you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j].  (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) 

Method4
Finally, you can use pointers-to-arrays:
 int (*array4)[NCOLUMNS] =
(int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
, but the syntax gets horrific and all but one dimension must be known at compile time.
Three Dimensional Array

#define MAXX 3
#define MAXY 4
#define MAXZ 5

main()
{
    int ***p,i,j;
    
p=(int ***) malloc(MAXX * sizeof(int ***));

    for(i=0;i
    {
        p[i]=(int **)malloc(MAXY * sizeof(int *));
        for(j=0;j
            p[i][j]=(int *)malloc(MAXZ * sizeof(int));
//allocating 1D array of size = size of last dimensional...So we have to allocate
//n1*n2 such arrays...where n1 and n2 are 2 such dimensional.
    }
     
    for(k=0;k
        for(i=0;i
            for(j=0;j
                p[i][j][k]=;

}

No comments:

Post a Comment