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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…