加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – calloc的等效代码

发布时间:2020-12-16 04:53:21 所属栏目:百科 来源:网络整理
导读:在给定的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;} 是
在给定的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的情况下执行此操作?我们如何使用malloc和c中的new来声明这个?

解决方法

calloc基本上等同于malloc,后跟memset将所有数据设置为零字节:
void *like_calloc(size_t size,size_t num) { 
    void *ret = malloc(size * num);

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

C为new提供了一种语法,使您可以更简单地执行此操作:

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

注意最后的parens.但是请注意,您通常不希望在C中执行此操作 – 您通常希望编写如下代码:

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;
}

这显然简化了代码的数量,但是有更多的简化,也可能是显而易见的.具体来说,这可以避免代码的其余部分必须跟踪何时不再需要返回值,并且在C版本或使用C中的新版本时根据需要删除内存(但不会更早).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读