Write a type definition for pointer variables that will be used to point to
dynamic arrays. The array elements are to be of type char. Call the type
CharArray.
#include <stdio.h>
#include <stdlib.h>
typedef char* CharArray;
int main() {
int size = 5;
CharArray arr = (CharArray)malloc(size * sizeof(char));
if (arr == NULL) {
printf("Failed to allocate memory for the array.\n");
return 1;
}
// Assign values to the dynamic array
arr[0] = 'H';
arr[1] = 'e';
arr[2] = 'l';
arr[3] = 'l';
arr[4] = 'o';
// Access and print the elements of the array
for (int i = 0; i < size; i++) {
printf("%c ", arr[i]);
}
printf("\n");
// Free the memory allocated for the array
free(arr);
return 0;
}
OUTPUT OF THE PROGRAM CODE:
H e l l o
NOTE:
In this example, we use the CharArray
type to declare a pointer variable arr
. We then dynamically allocate memory for an array of char
elements using malloc
. We can access and manipulate the elements of the array using the pointer arr
. Finally, we free the allocated memory using free
when we no longer need the array.