What's the best way to initialize a dynamically allocated boolean 2d array?

Advertisements

Just trying to (re)learn C and struggling with some basic concepts.

I’ve took a look this thread: How to memset an array of bools?.

According to that, it seems i may initialize a boolean 2d array like the following:

size_t size = sizeof(bool[4][3]);
bool (*ary)[4] = malloc(size);
memset(ary, false, size);

The problem i see with this code is that it depends on a boolean taking 1 byte, which i think is implementation dependant. Apart from that, the second parameter to memset according to my manual page (linux manpages project) seems to be an int… That manual page says "The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c". Isn’t this contradictory? If c is an int then it’s not a byte long.

EDIT1: See Ouroborus comment below about the last paragraph.

So after thinking a bit, i came up with the following code:

size_t size = sizeof(bool[4][3]);
bool (*ary)[4] = malloc(size);
const bool orig[4][3] = {
    {true, false, false},
    {false, true, true},
    {true, true, true},
    {false, false, false}
};
memcpy(ary, &orig, size);

This way i can initialize my memory not just with 0s (false), but with whatever i want. I’ve tested and this doesn’t work at all.

So my question is: What’s wrong with my code? And more important, what’s the way to do this?

Thanks!

>Solution :

Apart from the [4], there’s nothing wrong with your code. I would however recommend to use this:

bool (*ary)[3] = calloc(1, sizeof(bool[4][3]));
...
free(ary);

Done. Some notes:

  • Note the [3], not a 4. This is an array pointer pointing at bool [3] arrays. The reason why we use this over bool (*ary)[4][3] is because if we discard one dimension – which always has to be the left-most one – we can use the handy arr[i][j] syntax, which is much more readable than (*ary)[i][j].
  • Note that calloc will zero out the whole array as part of the allocation process. That’s pretty much the only reason why calloc exists in the first place.
  • If you need to init the array to something else than false then indeed use malloc + memcpy. But this will perhaps be a tiny bit slower than just one calloc call. Always prioritize code readability over micro-optimizations, however.

Leave a ReplyCancel reply