How to check if a pool is empty in C

I have the following code in C:

int i = 0; char delims[] = " \n"; char *result = NULL; char * results[10]; result = strtok( cmdStr, delims ); while( result != NULL ) { results[i] = result; i++; result = strtok(NULL, " \n"); } if(!results[1]) { printf("Please insert the second parameter...\n"); } else { ... } 

It always fulfills the else clause, even if results[1] empty.

I tried with results[1] == NULL , but did not succeed.

How to check if empty or not?

+7
source share
2 answers

Initialize the results array so that all elements are NULL :

 char* results[10] = { NULL }; 

In the published code, the elements are combined and will contain random values.

Also, prevent going beyond the results array:

 while (i < 10 && result) { } 
+9
source

There is no such thing as an "empty array" or an "empty element" in C. An array always contains a fixed predetermined number of elements, and each element always has a certain value.

The only way to introduce the concept of an “empty” element is to implement it yourself. You must decide which element value will be reserved for use as an "empty value". Then you have to initialize the elements of the array with this value. You will later compare the elements with this "empty" value to see if they are ... well, empty.

In your case, the array in question consists of pointers. In this case, choosing a null pointer value as a reserved value denoting an "empty" element is an obvious good choice. Declare an array of results as

 char * results[10] = { 0 }; // or `= { NULL };` 

check the items later as

 if (results[i] == NULL) // or `if (!results[i])` /* Empty element */ 
+5
source

All Articles