我想动态分配数组。 程序一:
#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
使用 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;
}