Advertisement
KattyG

Array add/delete to end

Jan 11th, 2020
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. // Implement a program to add to the end of an element and delete the last element to the dynes of the array
  2. // Implement the extension, deletion, and compression routines to the minimum
  3. // necessary volume of one-dimensional din. array of integers with adaptive increase.
  4. // In a situation where you need to request memory, request 20% more than necessary.
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. int *my_malloc(int size)
  9. {
  10.     int *array;
  11.     array = (int*)malloc(size * sizeof(int));
  12.     if (array == NULL)
  13.         return NULL;
  14.     return array;
  15. }
  16. void add(int **array, int *size, int new_value)
  17. {
  18.     *array = (int*)realloc(*array, (*size + 1) * sizeof(int));
  19.     *size = *size + 1;
  20.     (*array)[*size - 1] = new_value;
  21. }
  22.  void delete(int **array, int *size)
  23.  {
  24.      *array = (int*)realloc(*array, (*size - 1) * sizeof(int));
  25.       *size = *size - 1;
  26.  }
  27. void print_array(int *array,int size)
  28. {
  29.     for (int i = 0; i < size; i++)
  30.         printf("%d ", array[i]);
  31.     printf("\n");
  32. }
  33. int *expand(int *arr, int *new_size, int *max_size)
  34. {
  35.     int *tmp;
  36.     *max_size = (int) *new_size * 1.2;
  37.     tmp = realloc(arr, sizeof(int) * (*max_size));
  38.     if (!tmp)
  39.         return NULL;
  40.  
  41.     return tmp;
  42. }
  43.  
  44. void remove_arr(int *arr)
  45. {
  46.     free(arr);
  47. }
  48.  
  49. int *fit(int *arr, int *actual_size)
  50. {
  51.     int *tmp;
  52.     tmp = realloc(arr, sizeof(int) * (*actual_size));
  53.     if (!tmp)
  54.         return NULL;
  55.  
  56.     return tmp;
  57. }
  58.  
  59. int main()
  60. {
  61.     int *array;
  62.     int size = 5;
  63.     array = my_malloc(size);
  64.     for (int i = 0; i < size; i++)
  65.         array[i] = i;
  66.     print_array(array, size);
  67.     add(&array, &size, 5);
  68.     print_array(array, size);
  69.     delete(&array, &size);
  70.     print_array(array, size);
  71.     delete(&array, &size);
  72.     print_array(array, size);
  73.     free(array);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement