Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a character array is empty

Tags:

arrays

c

null

char

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

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

or

if(text[0] == '\0') {} 

or do i need to do

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

Whats the most efficient way to go about this?

like image 791
ZPS Avatar asked Nov 25 '09 00:11

ZPS


People also ask

What is in an empty char array?

The answer is: (char)0. Default values for primitives are 0, 0.0f, 0.0 (double), (char)0 and false (for boolean).

How can I tell if a character pointer is null?

Check the pointer for NULL and then using strlen to see if it returns 0 . NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior. Save this answer.

Does character array have NULL character?

// Pre: char array must have null character at the end of data. Thus, we first find out how long the data is. The variable length will be the index of the first null character in the array, which is also the length of the data.


1 Answers

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.

like image 137
bbum Avatar answered Sep 20 '22 14:09

bbum