简体   繁体   中英

pointers and char arrays( comparing)

I am trying to take out a given byte from a char array that has a pointer attached to it. see example below. (I have excluded headers etc.)

unsigned char compareByte(char *str, unsigned char byteNbr,
    unsigned char lengthOfStr, char char2compare)
{
  //I am stuck here, but this is what I tried to do
  if (byteNbr > lengthOfStr)
  {
    return (unsigned char) 0;
  }
  else
  {
    if (char2compare == *str + (byteNbr))
    {  //<- probably where it goes wrong
      return (unsigned char) 1;
    }
    else
    {
      return (unsigned char) 0;
    }
  }

}

int main()
{
  unsigned char result;
  char string[] = "abcdefg";
  unsigned char byte2Compare = 2; //want to take out 'b' from string
  result = compareByte(string, byte2Compare, strlen(string), 'b');
  if (result == 1)
  {
    printf("they match! \n");
  }
  else
  {
    printf("they don´t match!");
  }
}

I always get that "they don´t match" when I run it, do anyone have any idea how to make it work as planned?

I am thankful for any inputs.

Change if statement to below,

if( char2compare == *(str + byteNbr - 1) )

*(str + byteNbr - 1) This implies, dereferencing ( str at base address + 1 ( 2 - 1 )), which means value at address location of (str + 1) . Here 1 mean sizeof(char) bytes of next location.

Note: Arrays indexes always start from 0 . So when you say you want to look for byte 2 you actually mean array indexed at 1 .

Change

if(char2compare==*str+(byteNbr)){   

to

if(char2compare==*(str + byteNbr - 1)){   

*str+(byteNbr) is equivalent to a + 2 = c

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