Pelles C forum

C language => Expert questions => Topic started by: Snowman on March 05, 2016, 03:33:24 AM

Title: dynarray, a std::vector wannabe for C
Post by: Snowman on March 05, 2016, 03:33:24 AM
Hello, I've been coding a 100% macro-based dynamic array that is meant to be like a std::vector for C.

C++ users should find it very familiar, here's a basic usage example:

Code: [Select]
dynarray(int) dai;

dynarray_create(dai, 5);
dynarray_pushback(dai, 10);
dynarray_pushback(dai, 20);
dynarray_pushback(dai, 30);

for (const int *pi = dynarray_begin(dai); pi != dynarray_end(dai); ++pi)
    printf("%d ", *pi); // should print "10 20 30 "

printf("\n");
printf("%zu\n", dynarray_count(dai)); // should print "3"
dynarray_destroy(dai);

Naturally I am very interested in fixing bugs if they are found! Writing everything as macros is tricky but I want to be sure that memory leaks haven't been introduced.

Also, the attached source builds with a warning, which I would like to fix:
dynarray_test\dynarray_test.c(4): warning #2154: Unreachable code.

Edits:
Title: Re: dynarray, a std::vector wannabe for C
Post by: frankie on March 05, 2016, 05:33:02 PM
Nice.  :)
Title: Re: dynarray, a std::vector wannabe for C
Post by: Snowman on March 06, 2016, 12:10:15 PM
Right now I'm thinking to change the interface such that the macros will accept non-pointers. For instance:

Code: [Select]
// currently
dynarray_pushback(&dai, 0);
dynarray_pushback(&dai, 1);
dynarray_pushback(&dai, 2);

// after change
dynarray_pushback(dai, 0);
dynarray_pushback(dai, 1);
dynarray_pushback(dai, 2);

Doing the above would clean up code a little but I'm not sure if it's the right thing to do. Then again the macros are currently pretending to be functions when they're not, so that's probably not right either.

Any thoughts?
Title: Re: dynarray, a std::vector wannabe for C
Post by: frankie on March 06, 2016, 03:53:34 PM
Maybe this my old code could be of any help  ;)
Title: Re: dynarray, a std::vector wannabe for C
Post by: Snowman on March 06, 2016, 04:37:14 PM
Thanks for sharing. I see you went in the direction of using macros to declare functions whereas in my case macros are the functions. I think I'll stay on this road just to see how bad things get when I implement more complicated data structures.
Title: Re: dynarray, a std::vector wannabe for C
Post by: frankie on March 06, 2016, 04:57:28 PM
Yes I used generic functions and macros to enforce typechecking. I made this decision because using this code as a replacement in C++ modules, that I was porting to C, I need type checking to avoid errors (it was large code).
But it is just a way  :), you can use what you think it's better for you  ;)