Returning an array using C

前端 未结 8 1075
你的背包
你的背包 2020-11-21 04:45

I am relatively new to C and I need some help with methods dealing with arrays. Coming from Java programming, I am used to being able to say int [] method()in o

8条回答
  •  既然无缘
    2020-11-21 05:17

    How about this deliciously evil implementation?

    array.h

    #define IMPORT_ARRAY(TYPE)    \
        \
    struct TYPE##Array {    \
        TYPE* contents;    \
        size_t size;    \
    };    \
        \
    struct TYPE##Array new_##TYPE##Array() {    \
        struct TYPE##Array a;    \
        a.contents = NULL;    \
        a.size = 0;    \
        return a;    \
    }    \
        \
    void array_add(struct TYPE##Array* o, TYPE value) {    \
        TYPE* a = malloc((o->size + 1) * sizeof(TYPE));    \
        TYPE i;    \
        for(i = 0; i < o->size; ++i) {    \
            a[i] = o->contents[i];    \
        }    \
        ++(o->size);    \
        a[o->size - 1] = value;    \
        free(o->contents);    \
        o->contents = a;    \
    }    \
    void array_destroy(struct TYPE##Array* o) {    \
        free(o->contents);    \
    }    \
    TYPE* array_begin(struct TYPE##Array* o) {    \
        return o->contents;    \
    }    \
    TYPE* array_end(struct TYPE##Array* o) {    \
        return o->contents + o->size;    \
    }
    

    main.c

    #include 
    #include "array.h"
    
    IMPORT_ARRAY(int);
    
    struct intArray return_an_array() {
        struct intArray a;
        a = new_intArray();
        array_add(&a, 1);
        array_add(&a, 2);
        array_add(&a, 3);
        return a;
    }
    
    int main() {
        struct intArray a;
        int* it;
        int* begin;
        int* end;
        a = return_an_array();
        begin = array_begin(&a);
        end = array_end(&a);
        for(it = begin; it != end; ++it) {
            printf("%d ", *it);
        }
        array_destroy(&a);
        getchar();
        return 0;
    }
    

提交回复
热议问题