简体   繁体   中英

Confusions about if statement and strcmp with Strings

Here, I need some help in understanding the strings. I have a buff, which is flushed and then passed to a UART function. This buffer is now updated nad holding some value. I need to check the 5th byte of the buffer. What confuses me, I have written in code below. Please take a look.

int main()  
{  
  char buff[8];
  memset(buff,0,8);  

  /*  
       This buff is used by some UART function, and hence is updated by UART  
       This buff now holds some data. And now, I need to check the 5th byte it is holding.  
  */   

  if(buff[4]==0x04)  //will this work? or I need to use if(strcmp(buff[4],0x04))  ???
  {  
    //Do some functionality, for an example    
    printf("True");  
  }  
  else  
    printf("False");  

  return 0;  
}  

Your code is correct, yes.

Using strcmp() for this would only work if you know that the '\\x04' character is followed by a '\\0' string terminator. Since it looks like binary data, it would be very strange to use strcmp() .

You are not in any way comparing "strings", so using == is fine. In C, a "string" means "a (pointer to a) 0-terminated array of char ". That is not waht you're dealing with, so any lessons learned about how to deal with strings don't apply.

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