简单向量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int Type;
typedef struct vector {
size_t size;
size_t capacity;
Type *array;
} Vector;
Vector *vec_make(){
Vector *v;
v = (Vector*)malloc(sizeof(Vector));
v->size = 0;
v->capacity=16;
v->array=(Type*)realloc(NULL, sizeof(Type)*(v->capacity += 16));
return v;
}
void vec_pushback(Vector *v, Type value){
v->array[v->size] = value;
if(++v->size == v->capacity)
v->array=(Type*)realloc(v->array, sizeof(Type)*(v->capacity += 16));
}
size_t vec_size(Vector *v){
return v->size;
}
Type *vec_getArray(Vector *v){
return v->array;
}
void vec_free(Vector *v){
free(v->array);
free(v);
}
int main(){
int n=5;//user input
Vector *a, *b, *c;
int i, sum=0, size;
int *ap, *bp, *cp;
a = vec_make(); b = vec_make(); c = vec_make();
for (i=0; i<n; ++i) {
vec_pushback(a, i+1);//1,2,3,4,5
}
vec_pushback(b, 2);
vec_pushback(b, 4);
vec_pushback(b, 5);
vec_pushback(b, 6);
vec_pushback(b, 10);
ap=vec_getArray(a);bp=vec_getArray(b);cp=vec_getArray(c);
for(i=0;i<a->size;++i){
sum+=ap[i];
}
printf("sum(va)=%d\n", sum);
size=vec_size(b);
for(i=0;i<size;++i)
vec_pushback(c, ap[i]+bp[i]);
printf("va + vb = vc(");
for(i=0;i<size;++i){
printf("%d", cp[i]);
if(i<size-1)
printf(",");
else
printf(")\n");
}
vec_free(a);vec_free(b);vec_free(c);
return 0;
}