diff --git a/array.h b/array.h new file mode 100644 index 0000000..1740ef9 --- /dev/null +++ b/array.h @@ -0,0 +1,15 @@ +#include +#include "handle.h" + +/* Generic array macro */ +#define Array(T,AT) struct AT { \ + size_t count; \ + T *v; \ +}; handle(AT) { \ + if(state == HANDLE_CREAT) { \ + self->count = *(size_t*) data; \ + self->v = (T*) calloc(self->count, sizeof(T)); \ + } else if (state == HANDLE_DESTR){ \ + if(self->v) free(self->v); \ + } \ +} diff --git a/array_handle_gen_test.c b/array_handle_gen_test.c new file mode 100644 index 0000000..8f2e6b9 --- /dev/null +++ b/array_handle_gen_test.c @@ -0,0 +1,26 @@ +#include +#include +#include +#include "array.h" + +/* Prepare usage for 64 bit arrays - adds "Array_uint64" for creat */ +Array(uint64_t, Array_uint64); + +int main() { + int n; + printf("Number of elements to sum: "); + scanf(" %d", &n); + /* Create a 64 bit array of 'n' elements */ + creat(Array_uint64, data, &n); + // printf("vektor.count:%d\n", data.count); + + for(int i = 0; i < data.count; ++i) { + scanf(" %d", &n); + data.v[i] = n; + } + n = 0; for(int i = 0; i < data.count; ++i) n += data.v[i]; + printf("Sum: %d\n", n); + + // RAII releases array here automagicaly! + return 0; +} diff --git a/makefile b/makefile index 207de49..7046ba5 100644 --- a/makefile +++ b/makefile @@ -9,7 +9,11 @@ gcc: g++ raii_test.cpp -o raii_test_cpp gcc handle_test.c -o handle_test gcc array_handle_test.c -o array_handle_test - g++ array_handle_test.c -o array_handle_test_gpp + g++ array_handle_test.c -o array_handle_test_cpp + gcc array_test.c -o array_test + g++ array_test.c -o array_test_cpp + gcc array_handle_gen_test.c -o array_handle_gen_test + g++ array_handle_gen_test.c -o array_handle_gen_test_cpp clang: clang macroname.c -o macroname clang count.c -o count @@ -18,5 +22,6 @@ clang: clang construct_destruct.c -o construct_destruct # clang raii_test.c -o raii_test # should not work clang++ raii_test.cpp -o raii_test_cpp + clang++ array_handle_gen_test.c -o array_handle_gen_test_cpp expand: gcc -E handle_test.c -o handle_test_expanded.c