Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. enum { NVINIT = 1, NVGROW = 3 };
  5.  
  6. typedef struct vector vector;
  7. struct vector {
  8. int nval;
  9. int max;
  10. int *data;
  11. };
  12.  
  13. void print_vector(vector *v) {
  14. if (v == NULL) {
  15. return;
  16. }
  17.  
  18. for (int i = 0; i < v->nval; i++) {
  19. printf("%d\n", v->data[i]);
  20. }
  21. }
  22.  
  23. void add(vector *v, int val) {
  24. if (v == NULL) {
  25. return;
  26. }
  27.  
  28. if (v->data == NULL) {
  29. // first element in the vector
  30. // need to allocate memory for 1 element
  31. v->data = malloc(NVINIT * sizeof(int));
  32. v->nval++;
  33. v->data[0] = val;
  34. v->max = NVINIT;
  35. } else if (v->nval >= v->max){
  36. // grow size of the vector
  37. int *cp = realloc(v->data, (v->max * NVGROW) * sizeof(int));
  38.  
  39. for (int i = 0; i < v->nval; i++) {
  40. printf("hmm data = %d\n", v->data[i]);
  41. }
  42.  
  43. v->data = cp;
  44. v->max *= NVGROW;
  45. v->data[v->nval++] = val;
  46. } else {
  47. v->data[v->nval++] = val;
  48. }
  49. }
  50.  
  51. vector v;
  52.  
  53. int main() {
  54. for (int i = 0; i < 2; i++) {
  55. add(&v, i);
  56. }
  57. //print_vector(&v);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement