molecule molecule - 1 year ago 147
C Question

cannot convert argument of incomplete type 'void *' to 'const bitData'

I am trying to create a bit array in c++ and it works when I create a single variable. But I can't figure out how to fix this error when I am trying to create an array out of it.

typedef struct bitData
unsigned bit:1;
} bitData;

int main() {
bitData* buff;
*buff = malloc(3 * sizeof(struct bitData));
buff[0].bit = 1;
buff[1].bit = 0;
buff[2].bit = 1;

for (int i = 0; i < 3; ++i)
printf("buff[%d] = %d\n",i , buff[i].bit);

Here is the error :

$ g++ main.cpp
main.cpp:23:9: error: no viable overloaded '='
*buff = malloc(3* sizeof(struct bitData));
~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:12:16: note: candidate function (the implicit copy assignment operator) not viable: cannot convert argument of incomplete type 'void *' to 'const bitData'
typedef struct bitData
1 error generated.

Answer Source

*buff is an lvalue of type bitData. You can't assign a pointer to it.

In C, you can just say this:

buff = malloc(3* sizeof(struct bitData));

In C++ you cannot directly assign a void* to T*, you need to cast it:

buff = static_cast<bitData*>(malloc(3* sizeof(struct bitData)));

Although if you're using C++ you should use new rather than malloc, or, even better, containers/smart pointers to avoid manually managing memory.

If you want this part of code compatible with both C and C++, use C-style cast (be sure you really need to do this, though):

buff = (bitData*)malloc(3* sizeof(struct bitData));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download