C - 使用 strlen 使数组大小错误的数组初始化

标签 c arrays string initialization

我遇到了与 char 数组初始化的意外交互。

当初始化大小为 strlen( char parameter[] ) 的 char[] 时,新初始化的 char[] 太大。我不确定是什么原因造成的。

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

当我运行 foo 时,输出是

Length of testString: 6 

当我期望它是 1 时。


更奇怪的是,当我在 testString 初始化之前向 foo 添加打印语句时,输出似乎神奇地自行修复:

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 现在打印

Length of str: 1
Length of testString: 1

我感觉这与将 char[] 传递给函数的方式有关,或者可能是 strlen 的意外行为,但我真的不知道。

感谢任何帮助。

最佳答案

数组没有初始化

char testString[ strlen( str ) ];

因此将函数 strlen 应用于它会导致未定义的行为。

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

关于C - 使用 strlen 使数组大小错误的数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015037/

相关文章:

java - 使用二维数组查找列中的最大数字

Java 从数组列表中获取每个第二个元素并将其用作 HashMap 的值

string - (转义)字符串插值中的双引号(在 Swift 中)

c - 有没有什么方法可以更新并重新启动服务器并将其套接字保持在 "suspended"状态?

c - 用户扫描号码的模 10^9 + 7

c - 有效地使用 cuda 共享内存来存储字符

php - 显示 PHP 数组中值的计数

arrays - Haskell 中具有高性能的可变、随机访问数组/向量

java - 如何在 OSGI 包中包含 C 代码

python - 删除包含不同单词的行