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

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

最佳答案

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

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

关于C++关于堆栈上的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15085006/

相关文章:

C++:什么是 Mat3f?

c++ - 具有构造函数是否合适?

ios - 根据按钮数量设置 CollectionView 单元格高度

c++ - 构建发布/调试 VS2010 C++

arrays - 如何在 Postgres 中转换嵌套在另一个数组内的对象内的 JSON 数组?

php - 通过 ArrayAccess 访问多维数组

php - 对 2 深数组进行多排序

r - 如何在 R/Shiny 中布局动态生成的 UI 元素?

python - 使用 python 从文本文件创建动态 HTML 页面

c++ - 在 C++ 中对自定义对象的 vector 进行操作