Since an array name is actually a pointer to the first element within the array, it should be possible to define the array as a pointer variable rather than as a conventional array.For conventional array definition, a fixed block of memory is reserved at the beginning of program execution, but this does not occur in case of array represented in terms of pointer variable.Therefore, in order to represent an array, the use of a pointer variable requires some type of initial memory assignment before the array elements are processed.This is known as dynamic memory allocation. Generally, the malloc library function is used for this purpose.
Let us write a C program to illustrate the use of dynamic memory allocation.
/*reorder a one-dimensional, integer array from smallest to largest, using pointer notation*/
#include < stdio.h >
#include < stdlib.h >
void reorder (int n, int *x);
main()
{
int i, n, *x;
/*read in a value for n*/
printf("How many numbers will be entered? ");
scanf("%d", &n);
printf("\n");
/*allocate memory*/
x = (int *) malloc(n * sizeof(int));
/*read in the list of numbers*/
for (i =0;i < n;++i) {
printf("i = %d x = ", i+1);
scanf("%d", x+i);
}
/*reorder all array elements*/
reorder(n, x);
/*display the reordered list of numbers*/
printf("\n\nReordered list of numbers: \n\n");
for (i =0;i < n;++i)
printf("i = %d x = %d\n", i+1, *(x+i));
}
void reorder (int n, int *x) /*rearrange the list of numbers*/
{
int i, item, temp;
for (item=0; item < n-1; ++item)
/*find the smallest of all remaining elements*/
for (i = item+1; i < n; ++i)
if (*(x+i) < *(x+item)) {
/*interchange two elements*/
temp = *(x+ item);
*(x+ item) = *(x+ i);
*(x+ i) = temp;
}
return;
}
In this program, the integer array is defined as a pointer to a integer. The malloc library function is used to assign memory to the pointer variable.
We can also see that the scanf function specifies the address of ith element as x+i rather than x[i].
Within the function reorder,we can see that the second formal argument is now defined as a pointer variable rather than an integer array.In the if statement, we can see that x[i] is written as *(x+i), and x[item] as *(x+ item)
An advantage of dynamic memory allocation is that it is able to reserve as much as memory required during program execution, and then release the memory when it is no longer needed.
Wednesday, December 30, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment