Saturday, 1 November 2008

Construct Dynamic Array

In fact the title is not fairly accurate in the context since the Dynamic Array is not supported in C programming officially. Although some others language provide this latitude, C requires that the Array size have to be assign during the compile time instead of run time. In this case, the use of variable as the index of an Array such as: int x; int array[x]; is prohibited. The advantages of this sort of array usage are that the stack would not be complicated, the function call would not be expensive and the program would run faster.
However that doesn't mean that the Dynamic Array is impossible in C. The Dynamic Memory could be used to implement this function:

void main()
{
int *ptr = NULL;
int arr_size;
printf("Enter the size of array : ");
scanf("%d",&arr_size);
ptr = (int*) malloc(arr_size*(sizeof(int));
}

After this you can use ptr[0],ptr[1],.....ptr[n] as an array.

References: GeekInterview.com C programming interview questions 69 of 437

No comments: