使用strlen()设置char数组长度会返回错误的大小

时间:2022-03-25 18:33:26

I am trying to create a new c-string with the length of a passed in c-string. I set a variable to the length of the old string and then try to set a new c-string with that length but checking that length returns 1. Why does this happen?

我正在尝试创建一个新的c-string,其长度为传入的c-string。我将变量设置为旧字符串的长度,然后尝试设置一个具有该长度的新c字符串,但检查该长度返回1.为什么会发生这种情况?

//This function will return a pointer to a char array
char *encrypt(char plainText[], char code[]){
    int i = 0,j = 0;
    //length of plainText
    int len = strlen(plainText);
    printf("len %i\n",len); //8
    //I am declaring a pointer here
    char *x;
    //make a string for the cipherText
    char cipher[len];
    printf("cipher %lu\n",strlen(cipher)); //1
    return "Nothing";
}

1 个解决方案

#1


3  

The array cipher is uninitialized. It's contents is indeterminate (and will seem almost random). It might not contain the string-terminator at all, which means strlen will go out of bounds in its search for it. In your specific case you seem to be "lucky" that the second element in your array just happens to be the terminator.

阵列密码未初始化。它的内容是不确定的(并且看起来几乎是随机的)。它可能根本不包含字符串终结符,这意味着strlen在搜索它时会超出范围。在您的特定情况下,您似乎很“幸运”,您的数组中的第二个元素恰好是终结符。

And you seem to forget that char strings are really called null-terminated byte strings. That null-terminator also needs space. And exist of course.

而你似乎忘记了char字符串实际上被称为以空字符结尾的字节字符串。该null终结符也需要空间。当然存在。

All in all plenty of chances for undefined behavior.

总而言之,未定义的行为有很多机会。

#1


3  

The array cipher is uninitialized. It's contents is indeterminate (and will seem almost random). It might not contain the string-terminator at all, which means strlen will go out of bounds in its search for it. In your specific case you seem to be "lucky" that the second element in your array just happens to be the terminator.

阵列密码未初始化。它的内容是不确定的(并且看起来几乎是随机的)。它可能根本不包含字符串终结符,这意味着strlen在搜索它时会超出范围。在您的特定情况下,您似乎很“幸运”,您的数组中的第二个元素恰好是终结符。

And you seem to forget that char strings are really called null-terminated byte strings. That null-terminator also needs space. And exist of course.

而你似乎忘记了char字符串实际上被称为以空字符结尾的字节字符串。该null终结符也需要空间。当然存在。

All in all plenty of chances for undefined behavior.

总而言之,未定义的行为有很多机会。