Best way to check if a character array is empty

后端 未结 7 2025
臣服心动
臣服心动 2020-12-13 02:15

Which is the most reliable way to check if a character array is empty?

char text[50];

if(strlen(text) == 0) {}

or

if(text[         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 02:33

    Given this code:

    char text[50];
    if(strlen(text) == 0) {}
    

    Followed by a question about this code:

     memset(text, 0, sizeof(text));
     if(strlen(text) == 0) {}
    

    I smell confusion. Specifically, in this case:

    char text[50];
    if(strlen(text) == 0) {}
    

    ... the contents of text[] will be uninitialized and undefined. Thus, strlen(text) will return an undefined result.

    The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.

    char text[50];
    text[0] = 0;
    

    From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

提交回复
热议问题