Click here to Skip to main content
14,699,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i compare char name[10] with char *p;

What I have tried:

Im doing something like this

If(strcmp(name, p) == 0){
printf("something" );
}else printf("something else");

But these are never equal even if i know that they are
Updated 18-May-20 12:38pm

strcmp() should work just fine in this case. if it doesn't then name and what *p point to are different. Remember that strcmp() does not return true if the case is different (e.b. "Hello" is not equal to "hello") and it does not return true for substrings (e.g. "Hello" is not equal to "Hello world")
What happens if you do
printf("name = \"%s\"\n", name);
printf("*p   = \"%s\"\n", p);
printf("strcmp(name, p) = %d\n", strcmp(name, p));

if name and *p are equal, you should get a value of 0 for strcmp. If they are not equal, it should show up in the printfs. Perhaps you have trailing spaces or a trailing '\n' if you're getting input from a file or keyboard.
Just to add the k5054's comments, strcmp expects both strings to be null terminated: since name is a fixed-length string, it's possible that it's not terminated, and that means that it won't match a "proper" string.

There is also the strncmp[^] function which allows a max string length to compare, so if name is fixed length and may not be terminated, it may be a better choice for the comparison.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900