c++ - 静态与动态数组 C++

标签 c++ arrays dynamic static

C++ 编译器的行为可能不同。由于 C++ 中的数组可以使用以下方法声明:

方法一:

int size;
cout << "Enter size of array: ";
cin >> size;

int x[size];  
for (int i = 0; i < size; i++)
{
    //cout << "x[" << i << "] = ";
    x[i] = i + 1;
}  

方法B

int size;
cout << "Enter size of array: ";
cin >> size;

int *x = new int[size];  
for (int i = 0; i < size; i++)
{
    //cout << "x[" << i << "] = ";
    x[i] = i + 1;
}

通过在运行时 获取用户的输入,两者都可以正常工作。我知道,使用方法 B,我们必须像 delete [] x 一样删除 x

  • 为什么要使用 int *x = new int[size];,如果两者服务相同 目的?
  • 使用 new 有什么好处?

以下是我正在测试的代码片段:

#include<iostream>
using namespace std;

int main()
{
    int size;
    cout << "Enter size of array: ";
    cin >> size;

    //int *x = new int[size];
    int x[size];

    for (int i = 0; i < size; i++)
    {
        //cout << "x[" << i << "] = ";
        x[i] = i + 1;
    }

    cout << endl << "Display" << endl;
    for (int i = 0; i < size; i++)
    {
        cout << "x[" << i << "] = " << x[i] << endl;
    }  
    return 0;  
}

最佳答案

C++ 标准没有定义方法 A,但在 ISO C99 中是允许的,GCC 在 C++ 模式下也支持它。来自 https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html :

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

我刚刚在这里找到了一些相关的讨论:Variable Length Arrays in C++14?

关于c++ - 静态与动态数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866340/

相关文章:

ios - 我的按钮和 textview 没有显示在 iOS 的屏幕上?

c++ - 在 C++ 项目中链接 ITK 头文件

arrays - 使用数组的 Postgres 格式化字符串

javascript - 将多个数值合并为总计

javascript - 如何使用 JavaScript 排序对树 JSON 对象进行双重排序?

java - 带有字符串错误输出的 Switch 语句

android - 在 Android 应用程序中动态加载 fragment 时出错

c++ - set object = null 在 C++ 中的替代方法是什么,比如 C#

python - 设置嵌入式 Python 以编写 C++ 游戏脚本

c++ - 这是 lcov 的错误还是对一个函数中的不同命中计数有意义?