In C, a dynamic array is typically implemented using pointers and dynamic memory allocation, which allows for the size of the array to be determined at runtime rather than at compile time. Here is an example implementation of a dynamic array using these techniques:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array; // declare a pointer to int
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
// allocate memory for the array using malloc
array = (int *) malloc(size * sizeof(int));
// initialize the array elements
for (int i = 0; i < size; i++) {
array[i] = i * i;
}
// print the array elements
printf("Array elements:n");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("n");
// free the memory allocated for the array
free(array);
return 0;
}
In this example, we first declare a pointer to an integer called array and an integer variable called size. We then prompt the user to enter the desired size of the array, which we read into size using scanf.
Next, we use the malloc function to allocate memory for the array. We pass in the product of size and sizeof(int) to allocate the appropriate amount of memory for the array. The malloc function returns a pointer to the first element of the allocated memory block, which we assign to array.
We then use a for loop to initialize the array elements to the square of their index. Finally, we print out the array elements using another for loop and free the memory allocated for the array using the free function.
Note that because we allocated memory dynamically using malloc, we are responsible for freeing the memory using free when we are finished using the array. If we do not do so, we may encounter memory leaks or other memory-related errors.
Overall, dynamic arrays can be a useful tool in C programming, allowing for greater flexibility and dynamic memory allocation at runtime. By using pointers and dynamic memory allocation, C programmers can create dynamic arrays that can be resized and manipulated as needed to fit the requirements of their programs.