我们可以使用数组的最后一个元素吗?

Sah*_*are 0 c++ arrays

我有一个数组定义为arr[5].我可以填写并使用最后一个元素arr[5]=1000吗?如果是,那么'\0'将存储在数组中的哪个位置?此外,我不是在使用我没有声明的内存吗?

Ron*_*Ron 5

你不能使用,arr[5]因为那不是数组的最后一个元素.这会调用未定义的行为,就像你读出界限一样.数组的最后一个元素是arr[4].

空字符\0不是自动插入每个数组的东西.它总是插入到字符串文字中,而不是您的日常用户定义数组.

例如,这将起作用:

char arr[] = "Hello"; // array of 6 elements initialized with a string literal
                      // 5 for the characters plus 1 for the invisible \0
std::cout << arr[5];  // OK
Run Code Online (Sandbox Code Playgroud)

然而,这不会:

int arr[5] = { 1, 2, 3, 4, 5 }; // user defined array of 5 elements
std::cout << arr[5];            // Not OK! Reading out of bounds == UB
Run Code Online (Sandbox Code Playgroud)

因为没有这样的东西arr[5],也没有一个空字符附加到5个整数的数组.