为什么两者都没有任何问题,但首先它给出了某种类型的问题,其次却没有? [重复]

问题描述 投票:0回答:1

我想动态分配数组。 程序一:

#include <iostream>
using namespace std;
int main()
{
    int m,n;
    cout<<"enter the no of rows and column for dynamic array:";
    cin>>m>>n;
    int ptr[m][n];
}

节目2:

#include <iostream>
using namespace std;

int main()
{
    int m,n;
    cout<<"enter the no of rows and column for dynamic array:";
    cin>>m>>n;
    int **ptr;
    ptr=new int *[m];
    for(int i=0;i<m;i++)
    {
        ptr[i]=new int [n];
    }
}

程序 1 中的问题: 表达式必须有一个常量值。 变量“m”的值不能用作常量。 变量“n”的值不能用作常量。

我以前用过那种类型的程序,但以前没有给我这个问题。 我正在使用 g++ 编译器。 我尝试更改编译器并重新安装 mingw

c++ arrays pointers dynamic g++
1个回答
0
投票

使用 std::vector 进行动态内存分配。这样你就不会有内存泄漏(就像你的第二个例子)。请参阅:https://en.cppreference.com/w/cpp/container/vector

#include <iostream>
#include <vector>

// using namespace std; NO unlearn this 

int main()
{
    int rows, colums;
    std::cout << "enter the no of rows and column for dynamic array:";
    std::cin >> rows >> colums;
    int initial_value{ 3 };
    std::vector<std::vector<int>> values(rows, std::vector<int>(colums,initial_value));

    // https://en.cppreference.com/w/cpp/language/range-for
    for (const auto& row : values)
    {
        for (const auto value : row)
        {
            std::cout << value << " ";
        }
        std::cout << "\n";
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.