clearing a char array c

后端 未结 16 841
挽巷
挽巷 2020-12-07 10:31

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] = \         


        
相关标签:
16条回答
  • 2020-12-07 10:50

    An array in C is just a memory location, so indeed, your my_custom_data[0] = '\0'; assignment simply sets the first element to zero and leaves the other elements intact.

    If you want to clear all the elements of the array, you'll have to visit each element. That is what memset is for:

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

    This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:

    char *begin = &arr;
    char *end = begin + sizeof(arr);
    std::fill(begin, end, 0);
    
    0 讨论(0)
  • 2020-12-07 10:53

    I usually just do like this:

    memset(bufferar, '\0', sizeof(bufferar));
    
    0 讨论(0)
  • 2020-12-07 10:58

    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.

    0 讨论(0)
  • 2020-12-07 10:58

    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

    0 讨论(0)
  • 2020-12-07 10:59

    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?

    0 讨论(0)
  • 2020-12-07 10:59
    void clearArray (char *input[]){
        *input = ' '; 
    }
    
    0 讨论(0)
提交回复
热议问题