gpt4 book ai didi

c++ - 崇高文本 3 中的 ISO C++ 错误禁止可变长度数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:00 24 4
gpt4 key购买 nike

我最近更改了我的 C++ 编译器,我遇到了一个奇怪的错误,提示 ISO C++ 禁止可变长度数组。我清楚地记得我以前的编译器没有遇到这个错误。这是我编写的代码片段,只是为了检查这个新编译器的可靠性。

#include <iostream>
using namespace std;

int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}


In function 'int main()':
test.cpp:8:9: error: ISO C++ forbids variable length array 'a' [-Wvla]
int a[n]={0};

您会看到,即使用户在“n”中输入,编译器也会声明该数组具有可变长度。也欢迎提供有关其他编译器版本的建议!

最佳答案

std::vector 替换 VLA :

#include <iostream>
#include <vector>

int main()
{
int n;
std::cin>>n;
std::vector<int> a(n); // was VLA: int a[n];
for(int i=0;i<n;i++)
std::cin>>a[i];
for(int i=0;i<n;i++)
std::cout<<a[i]<<" ";
}

关于c++ - 崇高文本 3 中的 ISO C++ 错误禁止可变长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588338/

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