// Pantea Aria // Example: creating a dynamic array with malloc // then growing it later using realloc #include #include // TODO: write a function that creates and returns // a malloced array of given size int *build_array(int size); // TODO: write a function to print an array void show_array(int array[], int size); int main(void) { int size; printf("Enter initial size: "); scanf("%d", &size); // TODO: call build_array and check for NULL int *numbers = build_array(size); int i = 0; while (i < size) { numbers[i] = i * 2; //or any other value you want i++; } // TODO: print the original array show_array(numbers, size); // We decide the array needs to grow int new_size = size + 1; // TODO: use a temporary pointer with realloc int *temp = realloc(numbers, new_size * sizeof(int)); // TODO: check if realloc failed // if successful, update numbers if (temp != NULL) { numbers = temp; } else { printf("ERROR in realloc"); free(numbers); return 1; } // TODO: assign a value to the new element numbers[new_size - 1] = 99; // TODO: print the resized array show_array(numbers, new_size); free(numbers); // TODO: free the memory return 0; } int *build_array(int size) { int *p = malloc(size * sizeof(int)); return p; } void show_array(int numbers[], int size) { for (int i = 0; i < size; i++) { printf("%d ", numbers[i]); } printf ("\n"); }