如何清空char数组? [英] How to empty a char array?
问题描述
具有类似于char成员[255]的char数组.如何不使用循环将其完全清空?
Have an array of chars like char members[255]. How can I empty it completely without using a loop?
char members[255];
空"的意思是,如果其中存储了一些值,则应该没有.例如,如果我使用strcat,则旧值不应保留
By "empty" I mean that if it had some values stored in it then it should not. For example if I do strcat then old value should not remain
members = "old value";
//empty it efficiently
strcat(members,"new"); // should return only new and not "old value new"
推荐答案
使用
memset(members, 0, 255);
一般
memset(members, 0, sizeof members);
如果数组在范围内,则为
if the array is in scope, or
memset(members, 0, nMembers * (sizeof members[0]) );
如果只有指针值,并且nMembers是数组中的元素数.
if you only have the pointer value, and nMembers is the number of elements in the array.
编辑当然,现在要求已从清除数组的一般任务更改为纯粹重置字符串,memset
是过大的选择,只是将第一个元素清零就足够了(如其他答案中所述).
EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset
is overkill and just zeroing the first element suffices (as noted in other answers).
编辑为了使用 memset ,您必须包括string.h .
EDIT In order to use memset, you have to include string.h.
这篇关于如何清空char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!