简体   繁体   中英

C string and hex characters

Can anyone explain what is happening in this code?

    #include <stdio.h>

    void f(const char * str) {
      printf("%d\n", str[4]);
    }

    int main() {
      f("\x03""www""\x01""a""\x02""pl");
      f("\x03www\x01a\x02pl");
      return 0;
    }

why output is?

    1
    26

The issue is with "\\x01""a" versus "\\x01a" , and the fact that the hex->char conversion and the string concatenation occur during different phases of lexical processing.

In the first case, the hexadecimal character is scanned and converted prior to concatenating the strings, so the first character is seen as \\x01 . Then the "a" is concatenated, but the hex->char conversion has already been performed, and it's not re-scanned after the concatenation, so you get two letters \\x01 and a .

In the second case, the scanner sees \\x01a as a single character, with ASCII code 26.

In C, characters specified in hex (like "\\x01" ) can have more than two digits. In the first case, "\\x01""a" is character 1, followed by 'a'. In the second case, "\\x01a" , that's character 0x1a, which is 26.

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