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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h>
typedef int DataType; typedef struct array { DataType *Data; int size; int max_size; void (*Constructor)(struct array *); void (*Input)(DataType, struct array *); int (*get_array_size)(struct array *); int (*return_index_value)(struct array *, int); void (*print)(struct array*); void (*Destructor)(struct array *); }Array;
void Init(Array *this); void _print(Array *this); void _constructor(Array *this); void _denstructor(Array *this); void _input(DataType data, Array *this); int _get_array_size(Array *this); int _return_index_value(Array *this, int index);
void Init(Array *this) { this->Input = _input; this->print = _print; this->get_array_size = _get_array_size; this->return_index_value = _return_index_value; this->Constructor = _constructor; this->Destructor = _denstructor; this->Constructor(this); }
void _constructor(Array *this) { this->size = 0; this->max_size = 10; this->Data = (DataType*)malloc(this->max_size*sizeof(DataType)); memset(this->Data, 0, 10); }
void _input(DataType data, Array *this) { int i; DataType *ptr; if(this->size >= this->max_size) { this->max_size += 10; ptr = (DataType*)malloc(this->max_size*sizeof(DataType)); for(i=0; i<this->size; i++) ptr[i] = this->Data[i]; free(this->Data); this->Data = ptr; } this->Data[this->size] = data; this->size += 1; }
void _print(Array *this) { assert(this != NULL); Array *ptr = this; int i = 0; for(i=0; i<ptr->size; i++) printf("data is %d\n", ptr->Data[i]); }
int _get_array_size(Array *this) { assert(this != NULL); return this->size+1; }
int _return_index_value(Array *this, int index) { assert(this != NULL); return (this->Data[index]); }
void _denstructor(Array *this) { int i=0; assert(this != NULL); for(i=0; i<this->max_size; i++) this->Data[i] = 0; free(this->Data); }
int main(void) { Array my_array; Init(&my_array); my_array.Input(1, &my_array); my_array.Input(2, &my_array); my_array.Input(3, &my_array); my_array.Input(4, &my_array); my_array.print(&my_array); }
|