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?
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 */
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With