2

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.
molecule
  • 1,027
  • 1
  • 14
  • 27

3 Answers3

3

There is a typo in your code. The * in front of your pointer variable needs to go, you don't want to dereference it here, you want to assign to it.

In C:

int main() {
  bitData* buff;
  buff = malloc(3 * sizeof(struct bitData));

In a horrible C/C++ hybrid:

int main() {
  bitData* buff;
  buff = (bitData*)malloc(3 * sizeof(struct bitData));

In C++:

int main() {
  bitData* buff = new bitData[3];
nvoigt
  • 75,013
  • 26
  • 93
  • 142
2

*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));
krzaq
  • 16,240
  • 4
  • 46
  • 61
  • Then follow @user694733's advice. `vector` mayb be exactly what you want. What you're doing here is allocating 3 bytes, for 3 structs, even if you only use 1 bit of each. – krzaq Oct 21 '16 at 08:30
0

Just change the code as below and try:

typedef struct bitData
{
      unsigned bit:1;
} bitData;

int main() {
  bitData* buff;
  buff = (bitData*)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);
  }
}

Remove the * before buff and typecast it while allocating the memory. The above code will get compiled without any error or warning.

Stubborn
  • 780
  • 1
  • 5
  • 20