0

Which character has a bit representation of all zeroes?

For context, I'm wondering how to get a bit array of all zeroes and new to c/c++

unsigned char** result = (unsigned char**) malloc(sizeof(unsigned char)
                                                * rows);
for (int i = 0 ; i < rows ; i++) {
     result[i] = (unsigned char *) malloc(sizeof(unsigned char) * cols);
     memset(result[i], 0, sizeof(unsigned char) * cols);
   }

When I then try to print the bit representation (using c & 128, c & 64, i still get bits that are set)

For example: (for rows =3 and cols = 2)

00100000 00110111
00000000 00000000
00000000 00000000
user1018513
  • 1,682
  • 1
  • 20
  • 42
  • It looks ok, but could you show the full source including the part that prints out the result and sets the values of rows and cols? – Rein Oct 17 '14 at 22:06
  • 1
    This code is not correct; the first line needs allocating `rows` times the size of a `char *`. – Jongware Oct 17 '14 at 22:10
  • `malloc(sizeof(unsigned char*) * rows)`, `calloc(CHAR_BIT * cols + 1, sizeof(unsigned char))`, `memset(result[i], '0', CHAR_BIT * cols)` – BLUEPIXY Oct 17 '14 at 22:12
  • @Jongware Thanks! I'd completely missed the missing pointer.... solved the problem if you want to answer the question.. :) – user1018513 Oct 17 '14 at 22:16
  • Nah, go ahead and pick one of the others. (Although both repeat your own [casting of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc).) – Jongware Oct 17 '14 at 22:19

2 Answers2

1

In your first line, your malloc is allocating the wrong size. You are allocating for an unsigned char, when you should be allocating enough for a pointer to one, as below.

unsigned char** result = (unsigned char**) malloc(sizeof(unsigned char *) * rows);

This means the most significant bytes of your earlier pointers allocated within your loop are being clobbered by the succeeding malloc result. So when you look at result[i], you're not actually looking at the right place in memory any more.

sirlark
  • 2,187
  • 2
  • 18
  • 28
-1

It looks like you misuse type

unsigned char**

And you treat it like if it was an array, but it is just a pointer to pointer to unsigned char. Try replacing

unsigned char** result = (unsigned char**) malloc(sizeof(unsigned char) * rows);

with

unsigned char* result[] = new (unsigned char*)[rows];

then you can operate on variable result as on an array.

And replace

result[i] = (unsigned char *) malloc(sizeof(unsigned char) * cols);

with

result[i] = new unsigned char[cols];

When freeing memory you also need to call

delete[] result[i]; 

and

delete[] result; 

instead of

free()
mateo7
  • 11
  • 3