Home > other >  Why does the pointer to a character equal its value?
Why does the pointer to a character equal its value?

Time:04-24

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

CodePudding user response:

Actually, *foo is pointer dereferencing. Pointer itself is just foo and this one would not be equal 'f'.

CodePudding user response:

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.

  • Related