I found this trick/problem on the web and would like to understand what's happening.
#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
}
Everything worked as expected.
But when put a number after \0
sizeof
and strlen
both ignore \0
and the number next to it.
int main(){
char s[] = "S\065AB";
printf("%s ", s); // S5AB
printf("--- %d", sizeof(s)); // 5
printf(" -- %d", strlen(s)); // 4
}
Link to the above code: https://godbolt.org/z/7qfYq51E4
What's happening here?
CodePudding user response:
C provides for 1, 2 or 3 octal digits to be specified within a string.
In the first string char s[] = "S\0C5AB";
the single digit after the backslash is compiled to the value 0.
This definition is equivalent to:
char s[] = { 'S', 0, 'C', '5', 'A', 'B', '\0' }; // 0 == '\0'. They are the same
The second example posted contains 3 octal digits in sequence, and 065 == ASCII '5'
This means the 2nd example (char s[] = "S\065AB";
) is an array like this:
char s[] = { 'S', '5', 'A', 'B', '\0' }; // \065 ==> '5'