The*_*ore 0 c escaping c-strings
我在网上发现了这个技巧/问题,想了解发生了什么。
#include <stdio.h>
#include <string.h>
int main(){
char s[] = "S\0C5AB";
printf("%s", s);
printf("%d", sizeof(s)); // 7
printf(" -- %d", strlen(s)); // 1
}
Run Code Online (Sandbox Code Playgroud)
一切都按预期进行。
但是当在后面放一个数字时\0 sizeof,strlen两者都会忽略\0它旁边的数字。
int main(){
char s[] = "S\065AB";
printf("%s ", s); // S5AB
printf("--- %d", sizeof(s)); // 5
printf(" -- %d", strlen(s)); // 4
}
Run Code Online (Sandbox Code Playgroud)
上述代码链接: https: //godbolt.org/z/7qfYq51E4
这里发生了什么事?
C 规定在字符串中指定1、2 或 3 个八进制数字。
在第一个字符串中,char s[] = "S\0C5AB";反斜杠后面的单个数字被编译为值 0。
这个定义等价于:
char s[] = { 'S', 0, 'C', '5', 'A', 'B', '\0' }; // 0 == '\0'. They are the same
Run Code Online (Sandbox Code Playgroud)
发布的第二个示例包含按顺序排列的 3 个八进制数字,并且 065 == ASCII '5'
这意味着第二个示例 ( char s[] = "S\065AB";) 是一个如下所示的数组:
char s[] = { 'S', '5', 'A', 'B', '\0' }; // \065 ==> '5'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |