数组不是在C ++中动态分配的? [英] Are arrays not dynamically allocated in C++?

查看:141
本文介绍了数组不是在C ++中动态分配的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚在C ++中阅读了关于动态内存的教程,其状态如下:

I just read a tutorial about dynamic memory in C++ and it states as follows:


...常规数组的大小需要是常量表达式,因此其大小必须在此刻确定在设计程序之前,运行...

...the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run...

但是,我只是运行一个程序来测试这个:

However, I just ran a program to test this:

#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
    int y;
    cout << "Enter number of elements of array: ";
    cin >> y;
    int x[y];   // I declared an array using a variable size instead of a constant expression
    x[y-1] = 3;
    cout << x[y-1];

    return 0;
}

...没有错误。

推荐答案

不,他们不是。

您在这里看到的是一个名为可变长度数组的GNU扩展(仍然是基于堆栈的)。

What you're seeing here is a GNU extension called "variable length arrays" (which are still stack-based).

引用在

如果使用了正确的编译标志( -Wall -Wextra -pedantic )然后您的编译器会告诉您

If you used proper compilation flags (-Wall -Wextra -pedantic) then your compiler would tell you this.

这篇关于数组不是在C ++中动态分配的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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