清除字符数组 c [英] clearing a char array c
问题描述
我认为将第一个元素设置为 null 会清除 char 数组的全部内容.
I thought by setting the first element to a null would clear the entire contents of a char array.
char my_custom_data[40] = "Hello!";
my_custom_data[0] = '\0';
然而,这只会将第一个元素设置为空.
However, this only sets the first element to null.
或
my_custom_data[0] = 0;
而不是使用 memset
,我认为上面的 2 个例子应该清除所有数据.
rather than use memset
, I thought the 2 examples above should clear all the data.
推荐答案
这取决于您希望如何查看数组.如果您将数组视为一系列字符,则清除数据的唯一方法是触摸每个条目.memset
可能是实现这一目标的最有效方法.
It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset
is probably the most effective way to achieve this.
另一方面,如果您选择将其视为 C/C++ 空终止字符串,则将第一个字节设置为 0 将有效地清除字符串.
On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.
这篇关于清除字符数组 c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!