nathan1138
nathan1138

Reputation: 2645

Equivalent code for calloc

In the given c code snippet what will be the equivalent code for the line int *count = (int *)calloc(sizeof(int), 256); ?

int *getCharCountArray(char *str)
{
   int *count = (int *)calloc(sizeof(int), 256);
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
   return count;
}

Whether it is possible to do this without using calloc? How we can declare this using malloc and new in c++ ?

Upvotes: 14

Views: 11015

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490338

calloc is basically equivalent to malloc followed by memset to set all the data to zero bytes:

void *like_calloc(size_t size, size_t num) { 
    void *ret = malloc(size * num);

    if (ret)  
        memset(ret, 0, size * num);
    return ret;
}

C++ provides a syntax for new that lets you do this a little more simply:

int *count = new int[256]();

Note the parens at the end. Also note, however, that you generally do not want to do this in C++ at all -- you'd normally want to write the code something like this:

std::vector<int> getCharCountArray(unsigned char const *str) { 
     std::vector<int> count(std::numeric_limits<unsigned char>::max()+1);

     for (int i=0; str[i]; i++)
         ++count[str[i]];
     return count;
}

This obviously simplifies the code a fair amount, but there's more simplification than may be immediately obvious too. Specifically, this avoids the rest of the code having to track when the returned value is no longer needed, and deleting the memory at that point (but no sooner) as is needed with either the C version or the version using new in C++.

Upvotes: 14

Ben Voigt
Ben Voigt

Reputation: 283733

calloc is the same as malloc followed by memset

Upvotes: 2

Drew Dormann
Drew Dormann

Reputation: 63839

This will allocate 256 ints, and value-initialize the array to 0

This does what calloc is doing in your code.

int *count = new int[256]();
//                       ^^ value-initialization

Upvotes: 10

Related Questions