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
| #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
typedef enum elementTypes { String, Inter } elementType;
typedef struct { void *data; elementType type; } Element;
typedef struct { Element **data; size_t size; size_t capacity; } Array;
void init_array(Array *arr, int capacity) { arr->data = (Element **) malloc(capacity * sizeof(Element *)); arr->size = 0; arr->capacity = capacity; }
void free_array(Array *arr) { free(arr->data); arr->size = 0; arr->capacity = 0; }
void push(Array *arr, Element *element) { if (arr->size == arr->capacity) { arr->capacity *= 2; arr->data = (Element **) realloc(arr->data, arr->capacity * sizeof(Element *)); } arr->data[arr->size++] = element; }
void remove_element(Array *arr, size_t index) { assert(index < arr->size); arr->size--; memmove(&arr->data[index], &arr->data[index + 1], (arr->size - index) * sizeof(Element *)); }
Element *get(Array *arr, size_t index) { assert(index < arr->size); return arr->data[index]; }
void print_array(Array arr) { for (int i = 0; i < arr.size; i++) { Element *el = get(&arr, i); switch (el->type) { case String: printf("%s ", (char *) el->data); break; case Inter: printf("%d ", *(int *) el->data); break; default: printf("Unknown Type\n"); } } }
int main() { Array arr; init_array(&arr, 10); push(&arr, &(Element){.data = malloc(sizeof(int)), .type = Inter}); *((int *)arr.data[0]->data) = 10; push(&arr, &(Element){.data = malloc(sizeof(int)), .type = Inter}); *((int *)arr.data[1]->data) = 20; push(&arr, &(Element){.data = malloc(sizeof(int)), .type = Inter}); *((int *)arr.data[2]->data) = 30; push(&arr, &(Element){.data = strdup("zyimm"), .type = String}); print_array(arr); printf("\n"); remove_element(&arr, 0); print_array(arr); printf("\n"); free_array(&arr); return 0; }
|