'Why does the pointer to a character equal its value?
I was looking at my friend's code and found something that looked like this:
char foo[2] ="f";
if(*foo =='f'){
printf("%d",*foo);
}
I was wondering why this comparison evaluates true? I don't understand why the pointer to foo is the same as its value.
I understand that the standard thing to do would be to use strcmp for this kind of thing but was just wondering out of curiosity
Solution 1:[1]
Actually, *foo is pointer dereferencing. Pointer itself is just foo and this one would not be equal 'f'.
Solution 2:[2]
foo is an array, which degenerates into a pointer. So foo evalutes to an address
printf( "%p\n", (void*)foo ); // Print an address.
*foo is a dereference of that pointer, giving the value to which the pointer points.
printf( "%c\n", *foo ); // `f`
I understand that the standard thing to do would be to use strcmp
strcmp(foo, "f") == 0 is not equivalent to *foo == 'f' since the latter just checks the first character. However, strncmp(foo, "f", 1) == 0 would be equivalent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jakub Bednarski |
| Solution 2 |
