简体   繁体   English

动态分配数组

[英]Dynamic allocation of array

Why the below code compilation success though dynamic allocation of array is not possible in C++? 为什么在C ++中无法通过动态分配数组来实现以下代码编译成功? on uncommenting the comments it shows error?? 在取消注释它显示错误的评论?

#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";
    */
}

Because you appear to be using a compiler which allows this. 因为您似乎正在使用允许此操作的编译器。 VLAs in C++ are a GNU extension, any chance you are compiling this with g++ or clang++ ? C ++中的VLA是GNU扩展,您是否有机会用g++clang++编译它?

Set your compiler to strict ISO C++ mode, and it will warn you or error out. 将编译器设置为严格的ISO C ++模式,它将警告您或错误输出。

What I get from clang++ : 我从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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM