0

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!

4
  • Can you be more precise in how it don't work? What did you expect, and what happened instead? Commented Mar 13, 2014 at 18:38
  • 1
    Can you show how arr and X are declared? Also, are you trying to find a pointer to the same location in memory, or are you trying to find a matching string? Commented Mar 13, 2014 at 18:41
  • @pranitkothari , Uniq_names is the number of items in arr Commented Mar 13, 2014 at 18:43
  • @Gil.I Ya, got it after re-reading. Commented Mar 13, 2014 at 18:45

2 Answers 2

2

If you want to test if 2 strings are equal you can use the function strcmp declared in string.h.

Change if(X == arr[i]) to

if(strcmp(X, arr[i]) == 0)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

This will check if the first characters are equal, not the whole string.
True, I didn't realize OP was using them as strings. Editing my answer now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.