I am experiencing an unexpected interaction with char array initialization.
When initializing char [] with the size of strlen (char []), the newly initialized char [] is too large. I am not sure what causes this.
int main(void)
{
char myString[] = { " " };
foo( myString );
}
int foo( char str[] )
{
char testString[ strlen( str ) ];
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
When I run foo, the output
Length of testString: 6
when I expect it to be 1.
Even a stranger, when I add a print statement for foo before initializing testString, the result seems to magically commit itself:
int foo( char str[] )
{
printf( "Length of str: %lu\n", strlen( str ) );
char testString[ strlen( str ) ];
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
foo now prints
Length of str: 1
Length of testString: 1
I have a feeling that it has something to do with how char [] is passed into functions or perhaps the unexpected strlen behavior, but I really don't know.
Any help is appreciated.