Final answer:
The example C program demonstrates how to create a dynamic array using pointers and malloc, to populate it with user input, and to search for a number within that array.
Step-by-step explanation:
Creating a Dynamic Array in C
To create a dynamic array in C, you need to use pointers and the malloc function to allocate memory on the heap. Below is an example program that carries out the tasks specified:
#include
#include
int main() {
int *array, size, i, searchNumber, found = 0;
// Ask user to input the size of the array
printf("Please enter the size of the array: ");
scanf("%d", &size);
// Create a dynamic array using malloc
array = (int*)malloc(size * sizeof(int));
if(array == NULL) {
printf("Memory allocation failed\\");
return 1;
}
// Ask user to input the numbers to initialize the array
for(i = 0; i < size; i++) {
printf("Please enter the array element: ");
scanf("%d", &array[i]);
}
// Display the array elements
for(i = 0; i < size; i++) {
printf("element %d = %d\\", i, array[i]);
}
// Ask user to input the search number
printf("What number do you want to check: ");
scanf("%d", &searchNumber);
// Check if the number is in the array
for(i = 0; i < size; i++) {
if(array[i] == searchNumber) {
printf("Found number %d in array[%d]\\", searchNumber, i);
found = 1;
break;
}
}
if(!found) {
printf("Number %d not found in the array.\\", searchNumber);
}
// Clean up and free the dynamically allocated memory
free(array);
return 0;
}
This program requests the user to provide the size of the array, allocates memory for the array, allows the user to input elements to initialize the array, and then asks for a number to search within that array. The program searches for the provided number and prints the result. If the number is not found, it informs the user accordingly. Lastly, it frees the memory allocated for the array to avoid memory leaks.