gpt4 book ai didi

c++ - "NUL"字符 ("\0") 字节是分开的还是分配给带有字符串的字符数组?

转载 作者:太空狗 更新时间:2023-10-29 19:45:13 25 4
gpt4 key购买 nike

如果我定义一个字符串:

   char array[5] = {"hello"};

NUL 字符 (\0) 字节是否“隐藏”到“array[5]”,以便该数组在内存中不包含 5 个字节,而是包含 6 个字节?

或者 NUL 字符字节是否仅在字符数组的最后一个元素之后才与内存中的“array[5]”“分离”,而不是直接分配给“array[5]”?

如果我这样说:

  i = strlen(array);
printf("The Amount of bytes preserved for array: %d",i);

array[5] 保留的字节数的结果是什么?

“NUL”字符(“\0”)字节是在内存中字符数组的最后一个元素之后分开的,还是分配给该字符数组的?

最佳答案

Does the "NUL" character ("\0") byte lie separated after the last element of char-array in the memory or is it assigned to that char-array?

没有。两个答案都不正确。详情请见下文。


C 的答案:

如果您这样编写代码,显式大小对于终止符而言太小,array 将恰好包含 5 个元素,并且不会有 NUL 字符。

strlen(array) 具有未定义的行为,因为 array 不是字符串(它没有终止符)。 char array[5] = {"hello"}; 等同于 char array[5] = {'h', 'e', 'l', 'l', 'o '};.

另一方面,如果你写

char array[] = "hello";

相当于

char array[6] = {'h', 'e', 'l', 'l', 'o', '\0'};

strlen 将报告5

C标准的相关部分是:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

(强调我的。)


C++ 答案:

您的代码无效。 [dcl.init.string]状态:

There shall not be more initializers than there are array elements. [ Example:

char cv[4] = "asdf";            // error

is ill-formed since there is no space for the implied trailing '\0'. — end example ]

关于c++ - "NUL"字符 ("\0") 字节是分开的还是分配给带有字符串的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com