[英]C++ about dynamic array on stack
據我所知,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;
}
這些稱為可變長度數組 (VLA),是g ++編譯器擴展,不屬於C ++標准。 如果您希望代碼可移植,請不要在C ++中使用它。
您可以使用-Wvla
編譯標志使g++
發出警告,或者使用標志-Werror=vla
發出錯誤。 我通常使用-pedantic-errors
編譯,這可以捕獲這個以及許多其他偏離標准的錯誤。
C和C ++是不同的語言。 語言之間差異的一個例子是C 確實支持堆棧上的動態數組 (盡管C或C ++並不真正需要堆棧 )。 它們被稱為VLA(可變長度數組) : http : //en.wikipedia.org/wiki/Variable-length_array
g ++ 可能有一個擴展,允許在C ++中使用此功能,但所有C ++實現都不需要該擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.