【问题标题】:Conflicting declaration for 2d array in c++?c++中二维数组的声明冲突?
【发布时间】:2019-12-11 03:39:10
【问题描述】:

我遇到了一个需要动态声明二维数组的问题。 行数已知(即 2),而列数将作为输入。

我使用了这种技术:

cin>>size;
int **outer = new int*[2];
int outer[0] = new int[size];
int outer [1] = new int[size];

但这给出了一个错误:conflicting declaration 'int external [0]'

比我通过将代码更改为来解决问题:

cin>>size;       // size of the column
int **outer = new int*[2];
for(int i=0;i<2;i++)
       outer[i] = new int[size];

所以,我想知道为什么我不能像第一个那样声明二维数组,因为我在声明并定义了大小之后才声明它。

【问题讨论】:

    标签: arrays c++11 dynamic


    【解决方案1】:

    int outer[0] = ...;
    

    您将一个名为outer 的完全 变量定义为一个零元素数组。

    简单的分配似乎是你想要的:

    outer[0] = new int[size];
    outer[1] = new int[size];
    

    我真的建议您不要使用自己的手动内存和指针处理。第一个解决方法是意识到outer 不需要是指针而是数组,如

    int* outer[2] = {
        new int[size],
        new int[size]
    };
    

    然后使用 std::vector 完全消除指针,您可以这样做

    std::vector<int> outer[2] = {
        std::vector<int>(size),
        std::vector<int>(size)
    };
    

    您还应该考虑将 C 样式的数组替换为 std::array

    std::array<std::vector<int>, 2> outer = {
        std::vector<int>(size),
        std::vector<int>(size)
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多