Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if empty array in C

Tags:

arrays

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 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?

like image 285
user1893187 Avatar asked Dec 13 '12 22:12

user1893187


2 Answers

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 */
like image 60
AnT Avatar answered Nov 14 '22 18:11

AnT


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)
{
}
like image 20
hmjd Avatar answered Nov 14 '22 20:11

hmjd