clearing a char array c

后端 未结 16 815
挽巷
挽巷 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);
    

提交回复
热议问题