calloc
基本上相当于malloc
将memset
所有数据设置为零字节:
void *like_calloc(size_t size, size_t num) {
void *ret = malloc(size * num);
if (ret)
memset(ret, 0, size * num);
return ret;
}
C++ 提供了一种语法new
,让您可以更简单地执行此操作:
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++.