数组的动态分配

Dynamic allocation of array

本文关键字:动态分配 数组      更新时间:2023-10-16

为什么在C++中不能动态分配数组,却能成功编译以下代码?取消注释注释时显示错误??

#include<iostream>
#include <string>
using namespace std;
int main()
{
    string aa;
    cin>>aa;
    int a[aa.size()];// though allocating the array dynamically the compilation succeeded
    cout<<"COMPILATION SUCCESS"<<endl;
    /*char *p;
    cin>>p;
    int y=sizeof(p);
    int b[y];
    cout<<"COMPILATION ERROR"<<endl;
    */

    /*
    int tt;
    cin>>tt;
    int c[tt];//  shows error
    cout<<"ERROR";
    */
}

因为您似乎在使用允许这样做的编译器。C++中的VLA是GNU扩展,你有可能用g++clang++编译它吗?

将编译器设置为严格的ISO C++模式,它会发出警告或出错。

我从clang++:得到了什么

h2co3-macbook:~ h2co3$ clang++ -o quirk quirk.cpp -Wall -std=c++11 -pedantic
quirk.cpp:6:9: warning: variable length arrays are a C99 feature [-pedantic,-Wvla]
    char cs[s.size() + 1];
           ^
quirk.cpp:6:7: warning: unused variable 'cs' [-Wunused-variable]
    char cs[s.size() + 1];
         ^
2 warnings generated.