Reputation: 36205
I have an array which is of type **char which contains various values. I need to check whether the string is empty or NULL but no matter what I try it doesn't.
Below is the code I am currently using.
if (!strcmp(reportParameterArray[P_CALLINGPARTY], ""))
{
printf("****PERFORMING REPORT WITH RESTRICTIONS*****\n");
exit (0);
}
P_CALLINGPARTY is an ENUM value which is used to determine from what index within the array the value should be retrieve. I have tried using the above code as well as reportParameterArray[P_CALLINGPARTY] == NULL
, reportParameterArray[P_CALLINGPARTY] == ""
and reportParameterArray[P_CALLINGPARTY] = "\0"
neither of which work. It is always going into the if statement.
When I debug the code and print the value within gdb I get the following output.
print reportParameterArray[10]
$5 = 0x8062550 ""
Thanks for any help you can provide.
Upvotes: 0
Views: 134
Reputation: 409176
Check if the first character is the string terminator:
if (reportParameterArray[P_CALLINGPARTY][0] == '\0')
{
/* ... */
}
You can't use the equality operator ==
to compare strings, as it will only compare the pointer and not the string, and comparing to a literal string pointer will always be false.
Upvotes: 2
Reputation: 13171
If you have an array of strings (i.e., character pointers), and you want to test that one of its members is "empty", you really should check for both of two conditions: either that the array element is NULL, or that it is not null but 0 length. The safest way to do that is this:
char *array[];
. . .
if (NULL == array[i] || '\0' == *array[i]) {
<it's empty>
}
Upvotes: 2
Reputation: 9642
Your logic is perfectly fine, it's just the actual string comparison which is wrong.
Strings in C are character arrays, or in your case, char*
s, which are pointers to the first element in the string. This can work this way because a standard array can decay to a pointer to the first element in that array.
Anyway, assume I have two strings, "foo" and "bar", both stored in a char* like follows:
char* str1 = "foo";
char* str2 = "bar";
str1
and str2
will be pointers to the first character in each string, which is a memory address. str1
might point to 0x10, and str2
to 0x20, for example.
Now let's assign "foo" to str2
using str2 = "foo";
. This will actually change the memory address str2
points to, since it's a new string, so let's assume this is 0x30 for now.
Now, given str1 == 0x10
and str2 == 0x30
, and there's a string "foo" located at each, what happens if we run str1 == str2
? Despite them containing the same string, they the equality check doesn't work since they're at different addresses, and we're comparing the pointers.
Instead, there's a function strcmp
which does the comparison, and returns 0 if they match, so strcmp(str1, str2) == 0
.
tl;dr use strcmp
instead.
Upvotes: 0