Mehdi
Mehdi

Reputation: 93

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");
    }
 }

Upvotes: 0

Views: 245

Answers (2)

marcolz
marcolz

Reputation: 2970

Comparing char should be done with ==.

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

Upvotes: 0

P.P
P.P

Reputation: 121427

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.

Upvotes: 2

Related Questions