简体   繁体   中英

Comparing two Char in C

I have some trouble to compare the content of a message to verify if its correct But the problem is that I keep getting segmentation fault. here is my code :

int main()
{
    unsigned char rx_buffer[6];
    rx_buffer[0]='A';
    rx_buffer[1]='1';
    rx_buffer[2]='5';
    rx_buffer[3]='6';
    rx_buffer[4]='8';
    rx_buffer[5]='B';
    if (strcmp(rx_buffer[0],'A')==0 && strcmp(rx_buffer[5],'B')==0)
    {
        printf("Correct Message\n");
    }
 }

rx_buffer doesn't have NUL terminator. So you can't use strcmp() on it. Looking at your comparisons, you really wanted to compare chars. So use == operator:

if ( rx_buffer[0] == 'A' && rx_buffer[5] == 'B' ) {
     printf("Correct Message\n");
}

strcmp() is for comparing C-strings (A sewuence of characters terminated by a NUL byte) which is not what you have.

Comparing char should be done with == .

The strcmp() calls read past the end of rx_bytes[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM