我试图将“01”和“10”之类的值存储到一个数组中,但 int 数组会将“01”作为“1”。因此我决定使用字符串数组。在声明字符串数组时,我用
对其进行了初始化string array[n] = {0};
编译代码时显示错误:
"terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_constructnull not valid"
虽然只是将数组的类型更改为整数,但它工作正常。
我试着不初始化
string array[n]={0};
然后代码就可以正常工作了!
我们是否可以得出结论,字符串类型数组不能覆盖元素中已经存储的值?
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
string arr[n] = {0};
for(int i=0; i<n; i++){
cin>>arr[i];
cout<<arr[i];
}
}
这是代码的输出:
1
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_constructnull not valid
最佳答案
你有两个问题
string arr[n] = {0};
首先,n
不是编译时常量,因此 arr
是 VLA(可变长度数组)。这些不是标准的,仅作为某些编译器的扩展支持。您可以使用 -pedantic
编译器标志来停止编译。
其次,= {0}
部分将使用整数 0
初始化数组中的第一个字符串。由于 0
也是空指针值,因此它被视为指针,编译器会尝试从空指针构造字符串。这是未定义的行为,在这种情况下 std::string
会抛出异常。
要解决所有这些问题,请使用 std::vector
(可以具有运行时大小)并让它默认为您构建所有元素。你可以这样做
std::vector<std::string> arr(n);
关于c++ - 为什么当你用键盘输入覆盖元素中已经存储的值时,字符串类型的数组不取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711109/