1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include "dyn_array.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "utils.h"
struct Dyn_arry_t dyn_array_init(int* array, int size) { int* temp = malloc(sizeof(int) * size * 2);
if (temp) {
memcpy(temp, array, sizeof(int) * size); }
struct Dyn_arry_t my_array; my_array.array = temp; my_array.capacity = size * 2; my_array.size = size;
return my_array; }
void dyn_array_insert(struct Dyn_arry_t* array, int var) { if ((array->size) < (array->capacity)) { array->array[array->size] = var; array->size++; } else { printf("堆空间已用完\n"); int* temp = malloc(sizeof(int) * array->capacity * 2); if (temp) { array->capacity = array->capacity * 2; memcpy(temp, array->array, sizeof(int) * array->size); array->array = temp; array->array[array->size] = var; array->size++; } } }
void dyn_array_test(void) { Line("动态数组测试"); struct Dyn_arry_t darray; darray = dyn_array_init((int[]) { 1, 2, 3, 4, 5 }, 5); printf("动态数组测试\n"); print_array_int(darray.array, darray.size); for (int i = 40; i > 0; i--) { dyn_array_insert(&darray, i - 6); } printf("capacity:%d\n", darray.capacity); print_array_int(darray.array, darray.size);
free(darray.array); }
|