Another Method for Array of Variable Size
So, I have already introduced you to a new method to create an array of variable size but there is a drawback in that method.
(Those who have not red that method yet can have a look at it.
And the drawback is that you have to create another function to create that array and sometimes you need to enter a variable of which the array size is selected and that variable is to be entered in the middle of your program then you have to call the another function to create the array in middle of your program.And suppose if the variable in inside a loop then array is created so many times but you need only the first case.In that scenario, the previous method would not be suitable.
But for small programs that method is still valuable.
Here i am presenting you another method to do our job.
That method is based on the technique of dynamic memory allocation.Here what we do is that we create a pointer variable and then required size of memory is allocated of which our pointer points to the first place.
And then we can use it as a normal array.
Here is the sample program
main()
{
int i, *p, n;
scanf("%d",&n) ; //size of array
p=(int*)malloc(n*(sizeof(int))) ;
for(i=0 ; i<n ; i++)
p[i]=i ;
for(i=0 ; i<n ; i++)
printf("%d\n",p[i]) ;
}
for n=5
The output would be........
0
1
2
3
4
This method is totally okay.But there is still some drawback.As this method is based on dynamic memory allocation, it might be possible that during runtime, memory will not be able to be allocated.
So use it for limited array size (limits depend on the machine you are using).
Comments
Post a Comment
Comment on articles for more info.