起因 已经很少接触纯C语言项目,不过本着大道至简的念头,空暇时间可以写着玩玩,雕琢技艺, 目标 纯C实现动态数组,提供方便易用泛型接口,避免依赖 实现一 完全封装,隐藏结构
起因
已经很少接触纯C语言项目,不过本着大道至简的念头,空暇时间可以写着玩玩,雕琢技艺,
目标
纯C实现动态数组,提供方便易用泛型接口,避免依赖
实现一
完全封装,隐藏结构体细节,不支持栈创建
如果需要在栈使用,请自行修改(公开Vector细节,vector_init、vector_free声明)
vector.h
#ifndef VECTOR_H #define VECTOR_H #include <stddef.h> struct Vector_; typedef struct Vector_ Vector; Vector* vector_new(size_t elem_size); void vector_destory(Vector* v); size_t vector_length(Vector* v); void vector_append(Vector* v, void* elem_in); void vector_get(Vector* v, size_t pos, void* elem_out); void vector_set(Vector* v, size_t pos, void* elem_in); #endif // VECTOR_H
vector.c
#include <stdlib.h> #include <string.h> #include "vector.h" #define DEFAULT_VECTOR_SIZE 10 typedef unsigned char byte; typedef struct Vector_ { size_t size; size_t max_size; size_t elem_size; void* data; } Vector; static void vector_realloc(Vector* v) { v->data = realloc(v->data, v->elem_size*v->max_size); } static void vector_init(Vector* v, size_t elem_size) { v->size = 0; v->max_size = DEFAULT_VECTOR_SIZE; v->elem_size = elem_size; v->data = NULL; vector_realloc(v); } static void vector_free(Vector* v) { free(v->data); } Vector* vector_new(size_t elem_size) { Vector* v = realloc(0, sizeof(Vector)); vector_init(v, elem_size); return v; } void vector_destory(Vector* v) { vector_free(v); free(v); } size_t vector_length(Vector* v) { return v->size; } void vector_append(Vector* v, void* elem_in) { byte* p = v->data; if (v->size >= v->max_size) { v->max_size *= 2; vector_realloc(v); } p += v->elem_size * v->size; memcpy(p, elem_in, v->elem_size); v->size ++; } void vector_get(Vector* v, size_t pos, void* elem_out) { byte* p = v->data; if (pos < v->size) { p += v->elem_size * pos; memcpy(elem_out, p, v->elem_size); } } void vector_set(Vector* v, size_t pos, void* elem_in) { byte* p = v->data; if (pos < v->size) { p += v->elem_size * pos; memcpy(p, elem_in, v->elem_size); } }
测试
#include <stdio.h> #include <stdlib.h> #include "vector.h" int main(int argc, char *argv[]) { int test_data[] = {1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5}; size_t test_data_len = sizeof(test_data) / sizeof(int); Vector* v = vector_new(sizeof(int)); int i, x, y; for (i=0; i<test_data_len; i++) { vector_append(v, &test_data[i]); } printf("len:%d \n", vector_length(v)); for (i=0; i<test_data_len; i++) { vector_get(v, i, &x); printf("%d => %d \t", i, x); x *= 10; vector_set(v, i, &x); vector_get(v, i, &y); printf("%d => %d \n", i, y); } vector_destory(v); return 0; }
len:23 0 => 1 0 => 10 1 => 2 1 => 20 2 => 3 2 => 30 3 => 4 3 => 40 4 => 5 4 => 50 5 => 6 5 => 60 6 => 7 6 => 70 7 => 8 7 => 80 8 => 9 8 => 90 9 => 1 9 => 10 10 => 2 10 => 20 11 => 3 11 => 30 12 => 4 12 => 40 13 => 5 13 => 50 14 => 6 14 => 60 15 => 7 15 => 70 16 => 8 16 => 80 17 => 9 17 => 90 18 => 1 18 => 10 19 => 2 19 => 20 20 => 3 20 => 30 21 => 4 21 => 40 22 => 5 22 => 50