Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <limits.h>
  4.  
  5. #define __LEN(A) sizeof((A)) / sizeof((A)[0])
  6.  
  7. struct DynamicArray {
  8.     int * items;
  9.     int capacity;
  10.     int length;
  11. };
  12.  
  13. const int INITIAL_CAPACITY = 16;
  14.  
  15. void printArr(int len, int arr[]) {
  16.     // printf("%p: ", (void *)arr);
  17.     for (int i = 0; i < len; i++) {
  18.         printf("%i, ", arr[i]);
  19.     }
  20.     puts("");
  21. }
  22.  
  23. void printDynamicArray(struct DynamicArray * a) {
  24.     printf("Length (%i/%i): \n", a->length, a->capacity);
  25.     printArr(a->length, a->items);
  26. }
  27.  
  28. void addItemToArray(struct DynamicArray * a, int newValue) {
  29.     if (a->length == a->capacity) {
  30.         int newCapacity = a->capacity * 2;
  31.         a->items = realloc(a->items, newCapacity * sizeof(int));
  32.         a->capacity = newCapacity;
  33.     }
  34.     int pos = a->length;
  35.     a->items[pos] = newValue;
  36.     a->length++;
  37. }
  38.  
  39. int removeLastArrayItem(struct DynamicArray * a) {
  40.     if (a->length == 0) { return INT_MIN; }
  41.     int pos = a->length - 1;
  42.     int removedValue = a->items[pos];
  43.     a->length--;
  44.     if (a->length <= a->capacity / 3 && a->capacity > INITIAL_CAPACITY) {
  45.         a->capacity /= 2;
  46.         a->items = realloc(a->items, a->capacity * sizeof(int));
  47.     }
  48.     return removedValue;
  49. }
  50.  
  51. struct DynamicArray createArray() {
  52.     struct DynamicArray array = {
  53.         .items = malloc(INITIAL_CAPACITY * sizeof(int)),
  54.         .capacity = INITIAL_CAPACITY,
  55.         .length = 0
  56.     };
  57.     return array;
  58. }
  59.  
  60. int main() {
  61.     struct DynamicArray array = createArray();
  62.    
  63.     int number = 0;
  64.     do {
  65.         scanf("%i", &number);
  66.         addItemToArray(&array, number);
  67.     }
  68.     while (getchar() != '\n');
  69.     printDynamicArray(&array);
  70.    
  71.     free(array.items);
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement