0

为什么在 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";
    */
}
4

1 回答 1

2

因为您似乎正在使用允许这样做的编译器。C++ 中的 VLA 是 GNU 扩展,你有没有机会用g++or编译它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.
于 2013-06-27T13:17:16.223 回答