Monday, September 13, 2010

How to use Pointers for 2D Arrays

This is when, you want to have a two dimentional array and whos column size of fixed, but how many number of rows you need, you want to decide run time, in that case you may want to allocate memory for the whole 2D array dynamically. But the access to that array should be as simple as accessing it normally when declared using the standard syntax, i.e by using row and column numbers.

Remember that you cannot use, int **p for this purpose, or even int *p[4] for this purpose.

#include <stdio.h>
#include <malloc.h>

main()
{
    int i, j;
    int a[3][4];
    int (*p)[4];

    int size = 3;
    p = (int (*)[4])malloc(12*4);
    for(i=0; i<3; i++)
        for(j=0; j<4; j++)
        {
            p[i][j] = i+j;
            a[i][j] = p[i][j];
        }

    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }
}

Have a nice time, and enjoy programming.!

No comments:

Post a Comment