Search code examples
carraysbitmapbitcalloc

using calloc to create bitmap in C


If I use an int array as my bitmap, the size I allocate will be (1<<28)/32 right? because int is 32 bits...? And if I want to calloc this space before any functions are called, do I have to do anything special? Edit

I am trying to use calloc to have a bit array where I am able to check and set bits at that array location.

my attempt:

    int bitmap[] = calloc(1<<28, 1);

and

    int bitmap[] = (int*) calloc(1<<28, 1);

I am not sure what type the bitmap is or what to cast calloc to...

Any help would be appreciated!


Solution

  • You can't work directly with a "bit array" in C. You need to use masking / bitshift operators to access individual bits in larger units (at least an 8-bit char).

    Also, the correct syntax for what you're attempting is:

    int *bitmap = calloc(1<<28, sizeof(int));
    

    which will allocate an array of (1<<28) ints.

    Access them like this:

    int i;
    for (i = 0; i < (1<<28); ++i) {
        bitmap[i] = ...
    }