clearing a char array c

2019-01-16 03:02发布

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.

or

my_custom_data[0] = 0; 

rather than use memset, I thought the 2 examples above should clear all the data.

标签: c arrays char
16条回答
甜甜的少女心
2楼-- · 2019-01-16 03:47

How about the following:

bzero(my_custom_data,40);
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-16 03:48

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.

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-16 03:50

Try the following code:

void clean(char *var) {
    int i = 0;
    while(var[i] != '\0') {
        var[i] = '\0';
        i++;
    }
}
查看更多
我只想做你的唯一
5楼-- · 2019-01-16 03:50

Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.

查看更多
够拽才男人
6楼-- · 2019-01-16 03:50

set the first element to NULL. printing the char array will give you nothing back.

查看更多
成全新的幸福
7楼-- · 2019-01-16 03:50

Try the following:

strcpy(my_custom_data,"");
查看更多
登录 后发表回答