#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to insert an element into an array at a given position
int *insertElement(int *arr, int *size, int pos, int value) {
int *tmp;
// Allocate more memory to store the new element
tmp = realloc(arr, (*size + 1) * sizeof(int));
if (tmp == NULL) {
printf("Error allocating memory!\n");
return arr; // Return original array if memory allocation fails
}
arr = tmp; // Update pointer to newly allocated memory
(*size)++; // Increase size of the array
// Shift elements to the right to make space for the new element
for (int i = *size - 1; i > pos; i--) {
arr[i] = arr[i - 1];
}
// Insert the new element at the given position
arr[pos] = value;
return arr; // Return updated array
}
int main(void) {
int *p, i, size, pos, n;
// Prompt user for the array size
printf("Enter array size: ");
scanf("%d", &size);
// Allocate memory dynamically for the array
p = malloc(size * sizeof(int));
if (p == NULL) {
printf("Error allocating memory\n");
return 1; // Exit if memory allocation fails
}
// Seed random number generator and initialize array with random values
srand(time(NULL));
for (i = 0; i < size; i++) {
p[i] = rand() % 10 + 1; // Generate random numbers between 1 and 10
printf("arr[%d] = %d ", i, p[i]); // Print initial array
}
printf("\n");
pos = 2; // Define position for insertion
n = 888; // Value to be inserted
// Call the function to insert an element at position `pos`
p = insertElement(p, &size, pos, n);
// Print the updated array after insertion
printf("After insert:\n");
for (i = 0; i < size; i++) {
printf("arr[%d] = %d ", i, p[i]);
}
// Free allocated memory
free(p);
return 0;
}
/*
run:
Enter array size: 5
arr[0] = 9 arr[1] = 5 arr[2] = 1 arr[3] = 5 arr[4] = 3
After insert:
arr[0] = 9 arr[1] = 5 arr[2] = 888 arr[3] = 1 arr[4] = 5 arr[5] = 3
*/