C comparing pointers (with chars)

前端 未结 4 1098
我在风中等你
我在风中等你 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 08:56

    You need to use strcmp. Not seeing how you tried to use it, this is how you should use it:

    char *someother_char = "a";
    char *pointer = "a";
    
    if (strcmp(pointer, someother_char) == 0) { // match!
    }
    else { // not matched 
    }
    

    to then do the comparison with a char, you have to promote to a char*:

    char *someother_char1;
    char test = 'a';
    char *pointer = "a";
    
    strncpy((char*)test,someother_char1,sizeof(test));
    
    if (strcmp(pointer, someother_char1) == 0) { // match!
    }
    else { // not matched 
    }
    

    if you want to use the char array then you have to de-reference:

    char char_array[255];
    // don't forget to fill your array
    // and add a null-terminating char somewhere, such as char_array[255] = '\0';
    char *ptr_somechar = &char_array[0];
    char *pointer = "a";
    
    if (strcmp(pointer, ptr_somechar) == 0) { // match!
    } else { // not matched
    }
    

提交回复
热议问题