英文:
Why is that the both are working, but in first its giving some type of problem and in second it doesn't?
问题
Program 1 is giving an error because it's trying to create a 2D array with dimensions specified by variables "m" and "n," which is not allowed in standard C++. To dynamically allocate a 2D array, you should use Program 2. Program 2 uses pointers to create a dynamic 2D array, which is the correct way to allocate memory for a variable-sized array.
英文:
i want to dynamically allocate the array.
program 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];
}
program 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];
}
}
its giving problem in the program 1:
expression must have a constant value.
the value of variable "m" cannot be used as a constant.
the value of variable "n" cannot be used as a constant.
I was using that type of program before but it did not gave me this problem before.
I am using g++ compiler.
I tried changing the compiler and reinstalling mingw
答案1
得分: 1
Use std::vector for dynamic memory allocation. That way you will not have memory leaks (like in your second example). See : 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;
}
英文:
Use std::vector for dynamic memory allocation. That way you will not have memory leaks (like in your second example). See : 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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论