Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- enum { NVINIT = 1, NVGROW = 3 };
- typedef struct vector vector;
- struct vector {
- int nval;
- int max;
- int *data;
- };
- void print_vector(vector *v) {
- if (v == NULL) {
- return;
- }
- for (int i = 0; i < v->nval; i++) {
- printf("%d\n", v->data[i]);
- }
- }
- void add(vector *v, int val) {
- if (v == NULL) {
- return;
- }
- if (v->data == NULL) {
- // first element in the vector
- // need to allocate memory for 1 element
- v->data = malloc(NVINIT * sizeof(int));
- v->nval++;
- v->data[0] = val;
- v->max = NVINIT;
- } else if (v->nval >= v->max){
- // grow size of the vector
- int *cp = realloc(v->data, (v->max * NVGROW) * sizeof(int));
- for (int i = 0; i < v->nval; i++) {
- printf("hmm data = %d\n", v->data[i]);
- }
- v->data = cp;
- v->max *= NVGROW;
- v->data[v->nval++] = val;
- } else {
- v->data[v->nval++] = val;
- }
- }
- vector v;
- int main() {
- for (int i = 0; i < 2; i++) {
- add(&v, i);
- }
- //print_vector(&v);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement