11

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 executes the else condition even if the results[1] is empty.

I've tried with results[1] == NULL but no success.

How do I can check if it is empty or not?

hmjd
  • 120,187
  • 20
  • 207
  • 252
user1893187
  • 189
  • 2
  • 2
  • 8
  • [Best way to check if a character array is empty](http://stackoverflow.com/questions/1793867/best-way-to-check-if-a-character-array-is-empty) – ljedrz Dec 13 '12 at 22:32

2 Answers2

13

Initialize the results array so all elements are NULL:

char* results[10] = { NULL };

In the posted code the elements are unitialized and will be holding random values.

Additionally, prevent going beyond the bounds of the results array:

while (i < 10 && result)
{
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Is it correct to assume `= { NULL }` will set all indexes 0 to 9 to NULL? What if you want to set indexes 0 to 3 with some specific values, and fill the rest with NULL? Could I do something like `= { 0, 2, 3, 4, NULL }`, expecting it to fill the rest with the last element in the list? – mazunki Mar 20 '21 at 17:32
  • 1
    @mazunki It's correct to assume that array will be initialized from *0 to 9* as *NULL* and for your example initializing an array as `array[10] = {0,1,2,3,4}` the rest of the elements from *5 to 9* will initialize as *NULL*. You do not really need to specify *NULL* at the *4* index. – Spiros Gkogkas Apr 12 '21 at 16:47
8

There's no such thing as an "empty array" or an "empty element" in C. The array always holds a fixed pre-determined number of elements and each element always holds some value.

The only way to introduce the concept of an "empty" element is to implement it yourself. You have to decide which element value will be reserved to be used as "empty value". Then you'll have to initialize your array elements with this value. Later you will compare the elements against that "empty" value to see whether they are... well, empty.

In your case the array in question consist of pointers. In this case selecting the null pointer value as the reserved value designating an "empty" element is an obvious good choice. Declare your results array as

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

an later check the elements as

if (results[i] == NULL) // or `if (!results[i])`
  /* Empty element */
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765