C ++关于堆栈上的动态数组 [英] C++ about dynamic array on stack

查看:189
本文介绍了C ++关于堆栈上的动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So far as I know,C++/C doen't support dynamic array on stack . In the following 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;
}


推荐答案

=http://en.wikipedia.org/wiki/Variable-length_array =nofollow> 可变长度数组 (VLA),是一个g ++编译器扩展部分C ++标准。

These are called variable length arrays (VLA) and are a g++ compiler extension which is not part of the C++ standard. Do not use it in C++ if you want your code to be portable.

您可以使 g ++ 发出警告,但不要在C ++中使用它。与 -Wvla 编译标志或标志 -Werror = vla 的错误。我通常使用 -pedantic-errors 编译,捕获此错误和许多其他偏离标准。

You can make g++ emit a warning with the -Wvla compilation flag, or an error with flag -Werror=vla. I usually compile with -pedantic-errors, which catches this and many other deviations from the standard.

这篇关于C ++关于堆栈上的动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆