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 ;-)

No comments:

Post a Comment