简体   繁体   English

输出错误的错误

[英]Wrong strlen output

I have the following piece of code in C: 我在C中有以下代码:

char a[55] = "hello";
size_t length = strlen(a);
char b[length];
strncpy(b,a,length);
size_t length2 = strlen(b);
printf("%d\n", length);          // output = 5
printf("%d\n", length2);         // output = 8

Why is this the case? 为什么会这样呢?

必须为'b [length +1]'。strlen在c字符串的末尾不包含空字符。

You never initialized b to anything. 您从未将b初始化为任何东西。 Therefore it's contents are undefined. 因此,它的内容是不确定的。 The call to strlen(b) could read beyond the size of b and cause undefined behavior (such as a crash). 调用strlen(b)可能会超出b的大小,并导致未定义的行为(例如崩溃)。

b未初始化:运行程序时,它包含RAM中的所有内容。

For the first string a, the length is 5 as it should be "hello" has 5 characters. 对于第一个字符串a,长度为5,因为它应该是“ hello”,具有5个字符。

For the second string, b you declare it as a string of 5 characters, but you don't initialise it, so it counts the characters until it finds a byte containing the 0 terminator. 对于第二个字符串,b会将其声明为5个字符的字符串,但不对其进行初始化,因此它将对字符进行计数,直到找到包含0终止符的字节为止。

UPDATE : the following line was added after I wrote the original answer. UPDATE :在我写原始答案后添加了以下行。

strncpy(b,a,length);

after this addition, the problem is that you declared b of size length, while it should be length + 1 to provision space for the string terminator. 在添加之后,问题在于您声明了b的长度,而为字符串终止符提供空间时,它应该为length + 1。

Others have already pointed out that you need to allocate strlen(a)+1 characters for b to be able to hold the whole string. 其他人已经指出,您需要为b分配strlen(a)+1字符,才能容纳整个字符串。

They've given you a set of parameters to use for strncpy that will (attempt to) cover up the fact that it's not really suitable for the job at hand (or almost any other, truth be told). 他们为您提供了一组用于strncpy的参数,这些参数将(试图)掩盖一个事实,即它并不真正适合手头的工作(或者说实话,几乎所有其他工作)。 What you really want is to just use strcpy instead. 您真正想要的只是使用strcpy代替。 Also note, however, that as you've allocated it, b is also a local ( auto storage class) variable. 但是还要注意,在分配它时, b也是一个本地( auto存储类)变量。 It's rarely useful to copy a string into a local variable. 将字符串复制到局部变量中很少有用。

Most of the time, if you're copying a string, you need to copy it to dynamically allocated storage -- otherwise, you might as well use the original and skip doing a copy at all. 在大多数情况下,如果要复制字符串,则需要将其复制到动态分配的存储中-否则,您最好使用原始字符串,而根本不进行复制。 Copying a string into dynamically allocated storage is sufficiently common that many libraries already include a function (typically named strdup ) for the purpose. 将字符串复制到动态分配的存储中已经足够普遍了,以至于许多库已经为此包含了一个函数(通常称为strdup )。 If you're library doesn't have that, it's fairly easy to write one of your own: 如果您的图书馆没有这个库,那么编写自己的库就很容易了:

char *dupstr(char const *input) {
    char *ret = malloc(strlen(input)+1);
    if (ret)
        strcpy(ret, input);
    return ret;
}

[Edit: I've named this dupstr because strdup (along with anything else starting with str is reserved for the implementation.] [编辑:我将其命名为dupstr因为strdup (以及其他以str开头的内容都保留用于实现。)

Actually char array is not terminated by '\\0' so strlen has no way to know where it sh'd stop calculating lenght of string as as its syntax is int strlen(char *s)-> it returns no. 实际上char数组不是以'\\ 0'结尾,因此strlen无法知道它将停止计算字符串的长度,因为它的语法是int strlen(char * s)->它返回no。 of chars in string till '\\0'(NULL char) so to avoid this this we have to append NULL char (b[length]='\\0') 字符串中的char直到'\\ 0'(NULL char),所以要避免这种情况,我们必须追加NULL char(b [length] ='\\ 0')

otherwise strlen count char in string passed till NULL counter is encountered 否则,在字符串中使用strlen count char直到遇到NULL计数器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM