fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main() {
  5. int *arr, n, i, x, count = 0;
  6.  
  7. printf("Enter the size of the array: ");
  8. scanf("%d", &n);
  9.  
  10. arr = (int*) malloc(n * sizeof(int));
  11. if (arr == NULL) {
  12. printf("Memory allocation failed!\n");
  13. return 1;
  14. }
  15.  
  16. printf("\nEnter %d integers:\n", n);
  17. for (i = 0; i < n; i++) {
  18. scanf("%d", &arr[i]);
  19. }
  20.  
  21. printf("\nEnter the value to delete: ");
  22. scanf("%d", &x);
  23.  
  24. // Remove all occurrences of x
  25. for (i = 0; i < n; i++) {
  26. if (arr[i] != x) {
  27. arr[count++] = arr[i]; // overwrite deleted values
  28. }
  29. }
  30.  
  31. // Resize array using realloc
  32. arr = (int*) realloc(arr, count * sizeof(int));
  33. if (arr == NULL && count > 0) {
  34. printf("Memory reallocation failed!\n");
  35. return 1;
  36. }
  37.  
  38. printf("\nNew size of array: %d\n", count);
  39. printf("Updated array: ");
  40. for (i = 0; i < count; i++) {
  41. printf("%d ", arr[i]);
  42. }
  43.  
  44. free(arr);
  45. printf("\n\nMemory freed successfully.\n");
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0.01s 5320KB
stdin
10
1
2
3
4
1
2
3
1
1
4
1
stdout
Enter the size of the array: 
Enter 10 integers:

Enter the value to delete: 
New size of array: 6
Updated array: 2 3 4 2 3 4 

Memory freed successfully.