Reputation: 532
I'm experiencing an unexpected interaction with char array initialization.
When initializing a char[] with a size of strlen( char parameter[] ), the newly initialized char[] is too big. I am not sure what is causing 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 is
Length of testString: 6
when I am expecting it to be 1.
Even stranger is when I add a print statement to foo before the initialization of testString, the output seems to magically fix 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 the way char[] are passed into functions, or perhaps an unexpected behavior of strlen, but I really have no idea.
Any help is appreciated.
Upvotes: 4
Views: 1497
Reputation: 16540
remember two things:
and now the code:
#include <string.h> // strlen(), strcpy()
#include <stdio.h> // printf()
int main(void)
{
char myString[] = { " " }; <<-- actual length 2 (a space + a NUL )
foo( myString );
}
int foo( char str[] )
{
char testString[ strlen( str ) ]; <<-- strlen() yields 1, and testString not initialized
printf( "Length of testString: %lu\n", strlen( testString ) ); <<-- strlen searchs until a NUL byte found which could be anywhere
return 0;
}
Suggested corrections:
int foo( char str[] )
{
char testString[ strlen( str )+1 ];
strcpy( testString, str );
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
Note: the output of the above/corrected code is 1
, but the array testString[]
is actually 2 bytes
another way to do it is:
int foo( char str[] )
{
char testString[ strlen( str ) ] = {'\0'};
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
then the output would be 0
and the actual length of testString[]
is 1
Upvotes: 0
Reputation: 310970
The array was not initialized
char testString[ strlen( str ) ];
Thus applying the function strlen to it results in undefined behavior.
printf( "Length of testString: %lu\n", strlen( testString ) );
Take into account that you may not initialize a variable length array like testString
along with its declaration. You could write for example
char testString[ strlen( str ) ];
testString[0] = '\0';
It seems that what you mean is the sizeof
operator. If so you can write
printf( "Length of testString: %zu\n", sizeof( testString ) );
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
void foo( const char str[] )
{
char testString[ strlen( str ) ];
printf( "Length of testString: %zu\n", sizeof( testString ) );
}
int main(void)
{
char myString[] = { " " };
foo( myString );
return 0;
}
Its output is
Length of testString: 1
Upvotes: 5