Reputation: 71
I have newly begun to studdy C, so this might be a dumb question, but here it is:
first , I'm using this flags: -std=c99 -Wall
I got an array of char pointers, call it arr I also got a single char pointer, call it X I also know how many items(pointers) that does exist inside of arr, i got this number saved in an int called: Uniq_names
Now I'm wondering if there is a way to check if X does exist inside of arr
I have tryed to do it like this:
int i = 0;
while (i < Uniq_names){
if (X == arr[i]){
//do something
}
i++;
}
but it don't work, and i can't figure out why.
So why don't this work? and how can I do this check?
Edit 1: I did expect the code to get to the comment (here I use to have a print followed by an operation ) but it never did.
I know for a fact that a pointer to an object does exist in the array and are pointing to the same object as the pointer X are pointing to.
Say that arr is containing a pointer pointing to K, the pointer X that I'm comparing whith are also pointing to K, so this two pointers are the same (are they not?) but still the code inside of the "if" statement will never run.
Hope this made it clearer.
Edit 2:
Thank you guys!, problem where solved when I used strcmp!
Big thx!
Upvotes: 0
Views: 290
Reputation: 127
X == arr[i]
checks to see if the pointer (i.e. the memory address) is the same. If you're trying to see if the first char value is the same, you need to dereference both and compare the explicit value. In that case, you'd want *X == *arr[i]
.
To compare strings, you can use a simple for
loop.
bool matches;
char* X = arr[i];
int j = 0;
while *X!= NULL;{
if(X[j]==arr[i][j]){
matches = true;
j++;
}
else{
matches = false;
break;
}
This example is case sensitive.
Upvotes: 1