Total Pageviews

Friday 22 February 2013

STARTING ARRAY INDEX IN DYNAMIC MEMORY ALLOCATION:

When an array is created dynamically, the array index starts with 0. So make sure you start from 0th position and use till (n-1)th position.

Even if you try using from, say, 1 to n, the array values will be valid only till (n-1)th location. Hence the data stored in n th location will be lost.

EG:

int *array,array_size=5,i;
array=(int*)malloc(sizeof(int)*array_size);     
//THIS CREATES ARRAY OF SIZE 5 FROM INDEX 0 TO 4

printf("enter the array elements\n");
//IF YOU TRY TO USE 1 TO 5 LIKE BELOW....
for(i=1;i<=array_size;i++)
{
    scanf("%d",&array[i]);
}

//THE VALUE STORED IN array[n] VALUE WILL BE LOST
printf("array elements...\n");
for(i=1;i<=5;i++)
{
    printf("%d",array[i]);
}

OUTPUT:
enter the array elements
1 2 3 4 5
array elements...
1 2 3 4

What happens is, since the allocation for array starts at 0th index and ends at (n-1)th index, array[5] location is invalid. When the input is stored in this place, it is invalid and that is why 5 is missing when displaying array elements.

The conclusion of this post is, STRICTLY use the dynamically allocated array space from 0 th index till (n-1) th index. 

Thanks for reading my blog... Hope it gives a good point :-)
Post your comments which are always welcome ;-)

Saturday 2 February 2013

DYNAMIC MEMORY ALLOCATION OF 1-D AND 2-D ARRAYS

1-D ARRAY:

FORMAT:
datatype *ptr;
int size;
ptr=(datatype*)malloc(sizeof(datatype)*size);

EG:

#include<stdio.h>
#define SIZE 3

int main()
{
    int *array,i;
    array=(int*)malloc(sizeof(int)*SIZE);
    for(i=0;i<SIZE;i++)
    {
        array[i]=0;
        printf("%d\t",array[i]);
    }
    return 0;
}

OUTPUT:
0    0    0

2-D ARRAY:

FORMAT:
datatype **ptr;
int row_size,column_size,i;
ptr=(datatype**)malloc(row_size*sizeof(datatype*));
for(i=0;i<column_size;i++)
{
    ptr[i]=(datatype*)malloc(column_size*sizeof(datatype));
}

EG:

#include<stdio.h>
#define ROW 3
#define COL 3

int main()
{
    int **array,i,j;
    array = (int**)malloc(ROW*sizeof(int*));
    for (i=0; i<ROW; i++)
    {
        array[i] = (int*)malloc(COL*sizeof(int));
    }
    for (i=0; i<ROW; i++)
    {
        for (j=0; j<COL; j++)
        {
            array[i][j]=0;
            printf("%d\t",array[i][j]);
        }
        printf("\n");
    }
    return 0;
}

OUTPUT:
0   0   0
0   0   0
0   0   0