Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include "int_vector.h"
  2.  
  3. struct IntVector *newIntVector(int capacity)
  4. {
  5.     struct IntVector *vector = malloc(sizeof(struct IntVector));
  6.     if(capacity <= 0) return NULL;
  7.  
  8.     vector->data = malloc(capacity * sizeof(int));
  9.     vector->size = 0;
  10.     vector->capacity = capacity;
  11.  
  12.     return vector;
  13. }
  14.  
  15. void freeIntVector(struct IntVector *vector)
  16. {
  17.     free(vector->data);
  18.     vector->data = NULL;
  19.     vector->size = 0;
  20.     vector->capacity = 0;
  21. }
  22.  
  23. void pushIntVector(struct IntVector *vector, int value)
  24. {
  25.     if(vector->size < vector->capacity)
  26.     {
  27.         vector->data[vector->size++] = value;
  28.     }
  29.     else // reallocate internal buffer
  30.     {
  31.         int *buffer = malloc(2 * sizeof(int) * vector->capacity);
  32.         memcpy(buffer, vector->data, sizeof(int) * vector->size);
  33.         free(vector->data);
  34.         vector->data = buffer;
  35.         vector->capacity *= 2;
  36.  
  37.         vector->data[vector->size++] = value;
  38.     }
  39. }
  40.  
  41. bool popIntVector(struct IntVector *vector)
  42. {
  43.     if(vector->size > 0)
  44.     {
  45.         vector->size--;
  46.         return true;
  47.     }
  48.     return false;
  49. }
  50.  
  51. int *getIntVector(struct IntVector *vector, int index)
  52. {
  53.     if(index < 0 || index >= vector->size)
  54.         return NULL;
  55.     return &vector->data[index];
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement