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

查看:84
本文介绍了我们可以在 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天全站免登陆