关于堆栈上的动态数组的C ++

时间:2013-02-26 09:03:05

标签: c++ arrays dynamic

据我所知,C ++ / C不支持堆栈上的动态数组。 在以下说明中:

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;
}

2 个答案:

答案 0 :(得分:7)

这些被称为variable length arrays(VLA),是g ++编译器扩展,不属于C ++标准。如果您希望代码可移植,请不要在C ++中使用它。

您可以使g++使用-Wvla编译标志发出警告,或使用标记-Werror=vla发出错误。我通常使用-pedantic-errors编译,这可以捕获这个以及许多其他与标准的偏差。

答案 1 :(得分:1)

C和C ++是不同的语言。语言之间差异的一个例子是C 堆栈上支持动态数组(尽管堆栈 C或C ++并不真正需要)。它们被称为 VLA(可变长度数组)http://en.wikipedia.org/wiki/Variable-length_array

g ++ 可能具有允许在C ++中使用此功能的扩展,但并非所有C ++实现都需要该扩展。