C comparing pointers (with chars)

前端 未结 4 1101
我在风中等你
我在风中等你 2021-01-04 08:28

Good evening, I have 2 functions and each of them accepts as argument a pointer to char:

char pointer[255];
func1(char* pointer)
{
...
memcpy(pointer,some_ch         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 09:06

    Well right off the bat, if you want to compare the pointees, you need to dereference them. This means to compare the actual char value, you'll have to call

    if (*pointer == someother_char)
    

    However this will only compare the first char in the array, which is probably not what you want to do.

    To compare the whole thing strcmp should work

    char* someother_str = "hello strstr";
    if(strcmp(pointer, someother_str) == 0) {
        // do something
    }
    

    Make sure your other string is declared as a char*

    More info: http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

    Edit: as per your comment. comparing char* and char doesn't really make sense. One is a character value, the other is an address in memory. Do do so, you can either dereference the char* or reference the value variable.

    char c;
    char* ptr;
    
    // dereference ptr
    if ( c == *ptr ) {
       ...
    }
    
    // reference the value
    if ( &c == ptr ) {
    
    }
    

    The first method checks if the values are the same. The second checks if ptr is in fact pointing to the memory containing c ie. is ptr a pointer to c

    Hope that helps

提交回复
热议问题