Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <limits.h>
- #define __LEN(A) sizeof((A)) / sizeof((A)[0])
- struct DynamicArray {
- int * items;
- int capacity;
- int length;
- };
- const int INITIAL_CAPACITY = 16;
- void printArr(int len, int arr[]) {
- // printf("%p: ", (void *)arr);
- for (int i = 0; i < len; i++) {
- printf("%i, ", arr[i]);
- }
- puts("");
- }
- void printDynamicArray(struct DynamicArray * a) {
- printf("Length (%i/%i): \n", a->length, a->capacity);
- printArr(a->length, a->items);
- }
- void addItemToArray(struct DynamicArray * a, int newValue) {
- if (a->length == a->capacity) {
- int newCapacity = a->capacity * 2;
- a->items = realloc(a->items, newCapacity * sizeof(int));
- a->capacity = newCapacity;
- }
- int pos = a->length;
- a->items[pos] = newValue;
- a->length++;
- }
- int removeLastArrayItem(struct DynamicArray * a) {
- if (a->length == 0) { return INT_MIN; }
- int pos = a->length - 1;
- int removedValue = a->items[pos];
- a->length--;
- if (a->length <= a->capacity / 3 && a->capacity > INITIAL_CAPACITY) {
- a->capacity /= 2;
- a->items = realloc(a->items, a->capacity * sizeof(int));
- }
- return removedValue;
- }
- struct DynamicArray createArray() {
- struct DynamicArray array = {
- .items = malloc(INITIAL_CAPACITY * sizeof(int)),
- .capacity = INITIAL_CAPACITY,
- .length = 0
- };
- return array;
- }
- int main() {
- struct DynamicArray array = createArray();
- int number = 0;
- do {
- scanf("%i", &number);
- addItemToArray(&array, number);
- }
- while (getchar() != '\n');
- printDynamicArray(&array);
- free(array.items);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement