I'm using strlen
to get the length of a char array, sentence
.
When I run the following, the sentence
's length
is output as 12, despite being only 10 bytes wide:
/* mre.c */
#include <stdio.h>
#include <string.h>
int
main (void)
{
int length, i, beg;
char sentence[10] = "this is 10";
length = strlen (sentence);
printf ("length: %d\n", length);
for (i = 0; i < length; i++)
{
beg = 0;
}
return 0;
}
$ gcc mre.c && ./a.out
length: 12
When beg = 0;
is removed, it returns the expected result:
/* mre.c */
#include <stdio.h>
#include <string.h>
int
main (void)
{
int length, i, beg;
char sentence[10] = "this is 10";
length = strlen (sentence);
printf ("length: %d\n", length);
for (i = 0; i < length; i++)
{
/* beg = 0; */
}
return 0;
}
$ gcc mre.c && ./a.out
length: 10
I notice that if I print the sentence
a char at a time within a shell within Emacs, I see two extra chars:
/* mre.c */
#include <stdio.h>
#include <string.h>
int
main (void)
{
int length, i, beg;
char sentence[10] = "this is 10";
length = strlen (sentence);
printf ("length: %d\n", length);
for (i = 0; i < length; i++)
{
beg = 0;
printf ("%c", sentence[i]);
}
return 0;
}
$ gcc mre.c && ./a.out
length: 12
this is 10\0\0
I'm at a loss for how to explain this.