我们可以在C ++中创建可变长度数组吗 [英] Can we create variable length arrays in c++

查看:57
本文介绍了我们可以在C ++中创建可变长度数组吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的程序,该程序将数组的数据再次显示给用户.我想创建一个可变长度的数组.在此程序中,首先询问用户数组的元素数,然后是数据.

I am trying to create this simple program which displays the data of the array back to the user again.. I want to create a variable length array. In this program the user is first asked the number of elements of the array followed by the data.

问题在于,在某些IDE中,此代码可以完全正常运行,但在其他代码中,则出现错误,即不允许使用可变长度数组....那么正确吗?

The problem is that in some of the IDE this code runs completely fine but in others it gives the error that variable length array is not allowed.... So what is correct?

void main()
{
    int t;
    cin>>t;
    int ar[t];
    for(int i=0;i<t;i++)
    {
        cin>>ar[i];
    }

    for(int i=0;i<t;i++)
    {
        cout<<ar[i]<<"\t";
    }
}

例如这在 Turbo C ++ 中不起作用...但是可以在此IDE的环境中运行 http://www.tutorialspoint.com/compile_cpp11_online.php

For eg. This doesn't work in Turbo C++... But runs in this IDE's http://www.tutorialspoint.com/compile_cpp11_online.php

https://www.codechef.com/ide

推荐答案

标准C ++不支持可变长度数组.一些实现将它作为扩展提供,但是正如您已经发现的那样,依靠它们可以生成不可移植的代码.

Standard C++ does not support variable length arrays. Some implementations provide it as an extension but as you have already found out, relying on them makes for non-portable code.

我建议您改用 std :: vector .它可以与纯标准C ++一起使用.

I recommend you use a std::vector instead. It works with pure standard C++.

int size;
if (!(std::cin >> size) || (size < 0))
  throw std::invalid_argument {"bad size"};
std::vector<int> numbers (size);

在GCC和Clang中,您可以使用 -pedantic 编译器开关关闭所有非标准扩展名.这将帮助您避免意外编写不可移植的代码.当然,您还应该使用 -Wall -Wextra -Werror 进行编译.

In GCC and Clang, you can use the -pedantic compiler switch to turn off any non-standard extensions. This will help you avoid accidentally writing non-portable code. Of course, you should also compile with -Wall, -Wextra and -Werror.

这篇关于我们可以在C ++中创建可变长度数组吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆