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++ ?
The number of arguments in calloc() is 2. 3. malloc() is faster. calloc() is slower.
Calloc stands for contiguous allocation. Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.
Explanation: malloc() and calloc() return void *.
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++.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With