3

私の知る限り、C ++/Cはスタック上の動的配列をサポートしていません。次のdelcarationで:

int data[n] ; // if the n is not decided at compiling time ,this leads to error

しかし最近、私は次のように他の人のコードを読みました:

//**
It seems the n number can not be decided at compling time,but when I run it , if i fprintf the formation, each time i got the correct array size !!!!!!
the G++ version is 4.7.1 
Is this because the G++ 4.7.1 support C++11 x which allow dynamic array?
 **//

#include <cstdio>
#include <algorithm>
using namespace std;

#include <stdio.h>

char s[31];

int Hash()
{
    int sum=0;
    for(int i=0,k=0;k<7;i++)
    {
        if(s[i]>='0'&&s[i]<='9')
        {
            sum*=10;k++;
            sum+=(s[i]-'0');
        }
        else if(s[i]>='A'&&s[i]<'Z')
        {
            sum*=10;k++;
            sum+=((s[i]-'A'-(s[i]>'Q'))/3+2);
        }
    }
    return sum;
}

int main()
{

    int n;scanf("%d",&n);
    int data[n];getchar();
    //fprintf(stderr,"size is %d\n",sizeof(data)/sizeof(data[0]));
    //**
        It seems the n number can not be decided at compling time,but when I run it , if i fprintf the formation, each time i got the correct array size !!!!!!
     *//
    for(int tmp=0;tmp<n;tmp++)
    {
        gets(s);
        data[tmp]=Hash();
    }
    sort(data,data+n);
    bool p=false;n--;
    for(int i=0,num=1;i<n;i+=num=1)
    {
        while(data[i]==data[i+1])
        {
            num++;
            i++;
        }
        if(num>1)
        {
            printf("%03d-%04d %d\n",data[i]/10000,data[i]%10000,num);
            p=true;
        }
    }
    if(!p)printf("No duplicates.\n");
    return 0;
}
4

2 に答える 2

7

これらは可変長配列(VLA)と呼ばれ、C++標準の一部ではないg++コンパイラ拡張です。コードを移植可能にしたい場合は、C++で使用しないでください。

g++コンパイルフラグを使用して警告を発行し-Wvlaたり、フラグを使用してエラーを発行したりできます-Werror=vla-pedantic-errors私は通常、これと標準からの多くの他の逸脱をキャッチするでコンパイルします。

于 2013-02-26T09:04:45.760 に答える
1

C と C++ は異なる言語です。言語間の相違点の 1 つの例は、Cスタック上で動的配列をサポートしていることです (ただし、C または C++ ではスタックは実際には必要ありません)。それらはVLA (可変長配列)と呼ばれます: http://en.wikipedia.org/wiki/Variable-length_array

g++には、C++ でこの機能を可能にする拡張機能がある場合がありますが、その拡張機能はすべての C++ 実装に必要なわけではありません

于 2013-02-26T09:07:48.270 に答える