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 04:00

Why not use memset()? That's how to do it.

Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-16 04:01
void clearArray (char *input[]){
    *input = ' '; 
}
查看更多
闹够了就滚
4楼-- · 2019-01-16 04:05

Pls find below where I have explained with data in the array after case 1 & case 2.

char sc_ArrData[ 100 ];
strcpy(sc_ArrData,"Hai" );

Case 1:

sc_ArrData[0] = '\0';

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 97 'a'
[2] 105 'i'
[3] 0 ''

Case 2:

memset(&sc_ArrData[0], 0, sizeof(sc_ArrData));

Result:

-   "sc_ArrData"
[0] 0 ''
[1] 0 ''
[2] 0 ''
[3] 0 ''

Though setting first argument to NULL will do the trick, using memset is advisable

查看更多
冷血范
5楼-- · 2019-01-16 04:08

You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?

查看更多
登录 后发表回答