13

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?

1

2 Answers 2

14

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)
{
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
9

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 */

1 Comment

Can we check if the array is empty if we don't initialize it? int arr[10];.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.