我在网上发现了这个技巧/问题,想了解发生了什么。
#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
这里发生了什么事?