C - Initializing an array using strlen making array of the wrong size

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.

+4
2

char testString[ strlen( str ) ];

, strlen undefined.

printf( "Length of testString: %lu\n", strlen( testString ) );

, , testString, . ,

char testString[ strlen( str ) ];
testString[0] = '\0';

, sizeof. ,

printf( "Length of testString: %zu\n", sizeof( testString ) );

#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;
}

Length of testString: 1
+5

:

  • strlen() NUL char
  • 0, 1

:

#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;
}

: / 1, testString[] 2

:

int foo( char str[] )
{
    char testString[ strlen( str ) ] = {'\0'};
    printf( "Length of testString: %lu\n", strlen( testString ) );
    return 0;
}

0, testString[] 1

0

Source: https://habr.com/ru/post/1668685/


All Articles