这是一个“它是如何工作的”问题。根据我的理解,您必须使用恒定数量的元素 (int intarr[5]) 初始化一个非动态数组,否则您的数组将覆盖可能分配给其他内容的内存块。
那么为什么你可以初始化一个没有任何元素的字符串数组(string strArray[])?
示例:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s[] = {"hi", "there"};
cout << s[0] << s[1];
cin >> s[10]; //why is this ok?
cout << s[10];
return 0;
}
最佳答案
作为 C++(和 C)的一项功能,如果您为其指定了初始值设定项,则可以在不指定元素数量的情况下声明数组。编译器将推断所需的元素数量。
所以对于
int intarr[] = { 1,2,3,4,5};
编译器会发现数组需要有 5 个整数的空间,这将与您所说的完全相同:
int intarr[5] = {1,2,3,4,5};
字符串数组也是一样的;
string s[] = {"hi", "there"};
和你写的一样
string s[2] = {"hi", "there"};
你的代码有一个严重的错误;
string s[] = {"hi", "there"};
cout << s[0] << s[1];
cin >> s[10]; //why is this ok?
cin >> s[10];
绝对不行。数组s
只有2个元素,即使编译器没有产生错误,也不能使用s[10]
这样做的结果是 undefined behavior - 所以它可能看起来可以工作,或者可能崩溃,或者它可以做任何事情。
关于C++ 为什么可以初始化一个空字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18859172/