In C programming please give an example and explanation of: I want to know how to make an add function to add the user input to the end of an array that’s been dynamically allocated in the main function/also using a structure. Each time the user adds an element to the array it will be added to the end of the array and the array will increment up once each time as the value/data is added. Would it also be good practice to use realloc to resize the array every time an element is added in the add function? If so please show that too. Thank you very much. In C programming please give an example and explanation of: I want to know how to make an add function to add the user input to the end of an array that’s been dynamically allocated in the main function/also using a structure. Each time the user adds an element to the array it will be added to the end of the array and the array will increment up once each time as the value/data is added. Would it also be good practice to use realloc to resize the array every time an element is added in the add function? If so please show that too. Thank you very much.
Explanation / Answer
#include #include int main() { int i, num, size = 0, cap = 2; int *arr = (int *)malloc(sizeof(int)*cap); while(1) { printf("Enter a number(-1 to exit): "); scanf("%d", &num); if(num == -1) { break; } if(size == cap) { cap++; arr = (int *)realloc(arr, sizeof(int)*cap); } arr[size++] = num; } // print array for(i = 0; i