eteran / c-vector

A dynamic array implementation in C similar to the one found in standard C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't push_back with custom struct.

MubinMuhammad opened this issue · comments

I have this "complex" data structure and cvector()-ing it doesn't show any error (as it's just "type *"), error happens when i try to cvector_push_back(). Here's the code:

struct complex {
  const char *compiler;
  const char *program_name;
  const char *program_type;
};

cvector(struct complex) test_var = NULL;

/*
* give me this error: "to many arguments provided to function-like macro invocation" 
* (by the way i'm using clangd)
*/
cvector_push_back(test_var, (struct complex){"gcc", "something"});

// gives the same error
cvector_push_back(test_var, (struct complex){
  .compiler = "gcc",
  .program_name = "something"
});

I hope it's an easy problem to fix, Thanks.

So, the problem is that (struct complex){"gcc", "something"} has a comma in it.

C's macro parser is pretty naive and doesn't deal with this well. I'll see if there is a workaround, but the simplest thing you can do is just something like this:

struct complex {
    const char *compiler;
    const char *program_name;
    const char *program_type;
};

int main() {
    cvector(struct complex) test_var = NULL;

    struct complex c = {
        .compiler     = "gcc",
        .program_name = "something"};

    cvector_push_back(test_var, c);
    return 0;
}

Aha! just needed an extra paranthesis!

struct complex {
    const char *compiler;
    const char *program_name;
    const char *program_type;
};

int main() {
    cvector(struct complex) test_var = NULL;
    cvector_push_back(test_var, ((struct complex){"gcc", "something"}));
    return 0;
}