Reputation: 4316
I have char *words[]
that holds strings of varying length.
Let words
contain 5 dynamically allocated strings: ["zero","one","two","three","four"]
.
I free one of the strings and set its pointer to NULL
like so:
free(words[1]);
*(words[1]) = NULL;
Later on I loop through the words
array and check if each item is NULL
like so:
if(*words[i] == NULL)
And when I compile gcc says warning: comparison between pointer and integer
. A bit of googling has shown me that I can silence this warning by changing the check to:
if(*words[i] == 0)
or if(*words[i])
I know its nitpicky, but these checks just aren't as clear as it would be if it used NULL
. Is there a way to compare using NULL
without altering gcc flags or using a #define
-esque solution?
As a reference, my compile command is:
gcc -m32 -g -O0 -std=gnu99 -Wall -Wfloat-equal -Wtype-limits -Wpointer-arith -Wlogical-op -fno-diagnostics-show-option -m32 words.c -o words
Upvotes: 1
Views: 517
Reputation: 1626
The code isn't doing what you think it is. *words[i]
gives you the first character in the ith string (i.e. a char
), not the ith string itself (i.e. a char*
). What you want is just words[i]
. Remember that in C char* words[]
is basically char** words
.
The warning comes from the fact that C considers char
to be an integer. In this case, it is a good thing the compiler warned you!
Upvotes: 7