Can anyone explain why this code:
char t1[20];
char t2[20];
memset(t1, 'B', sizeof(t1));
memset(t2, 'B', sizeof(t2));
printf("%lu\n", strlen(t1));
printf("%lu\n", strlen(t2));
result in:
22
21
Thank's
Can anyone explain why this code:
char t1[20];
char t2[20];
memset(t1, 'B', sizeof(t1));
memset(t2, 'B', sizeof(t2));
printf("%lu\n", strlen(t1));
printf("%lu\n", strlen(t2));
result in:
22
21
Thank's
strlen
expects to be given a (pointer to a) C string. A C string is an array of char
terminated with the null character, '\0'
.
When you memset
your char
arrays, you just write a 'B'
into every element, thus neither of these arrays is a C string. Passing them to strlen
is undefined behavior.
In order to fix this, set the last element of each array accordingly:
t1[19] = '\0';
t2[19] = '\0';