如何memset char数组与null终止字符? [英] How to memset char array with null terminating character?

查看:232
本文介绍了如何memset char数组与null终止字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用null终止字符来设置整个字符数组的正确和最安全的方法是什么?我可以列出几个用法:

What is the correct and safest way to memset the whole character array with the null terminating character? I can list a few usages:

...
char* buffer = new char [ARRAY_LENGTH];

//Option 1:             memset( buffer, '\0', sizeof(buffer) );
//Option 2 before edit: memset( buffer, '\0', sizeof(char*) * ARRAY_LENGTH );
//Option 2 after edit:  memset( buffer, '\0', sizeof(char) * ARRAY_LENGTH );
//Option 3:             memset( buffer, '\0', ARRAY_LENGTH );
...






  • 使用1,2或3可以解决什么样的问题?

  • 处理此要求的最佳方式是什么?

  • 推荐答案

    选项一和选项二。第一个使用指针的大小而不是数组的大小,因此它可能不会写入整个数组。第二个使用 sizeof(char *)而不是 sizeof(char),所以它会写入数组的末尾。选项3是好的。您还可以使用此

    Options one and two are just wrong. The first one uses the size of a pointer instead of the size of the array, so it probably won't write to the whole array. The second uses sizeof(char*) instead of sizeof(char) so it will write past the end of the array. Option 3 is okay. You could also use this

    memset( buffer, '\0', sizeof(char)*ARRAY_LENGTH );
    

    sizeof(char)为1。

    这篇关于如何memset char数组与null终止字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆