13

在给定的 c 代码片段中,该行的等效代码是 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;
}

是否可以在不使用 calloc 的情况下做到这一点?我们如何在 c++ 中使用 malloc 和 new 声明它?

4

3 回答 3

12

calloc基本上相当于mallocmemset所有数据设置为零字节:

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++.

于 2013-03-30T21:09:55.543 回答
10

这将分配 256 个整数,并将数组值初始化0

这会calloc在您的代码中执行此操作。

int *count = new int[256]();
//                       ^^ value-initialization
于 2013-03-30T21:07:15.320 回答
2

callocmalloc与后面相同memset

于 2013-03-30T21:07:18.083 回答