this is my code i wanted to return a 2d array from a function and use it in other function inorder to modify it.
#include<bits/stdc .h>
using namespace std;
int** createMat(int row,int col){
int arr[row][col];
for(int i=1;i<=row;i ){
for(int j=1;j<=col;j ){
cin>>arr[i][j];
}
}
return arr;
}
int main(){
int row,col;
cin>>row;
cin>>col;
createMat(row,col);
}
CodePudding user response:
You should use containers. They are the bread and butter of C .
Please follow the advice of Some programmer dude. Invest in a good C book.
#include <vector>
#include <iostream>
std::vector<std::vector<int>> createMat(int row, int col)
{
std::vector<std::vector<int>> data;
data.resize(row);
for (auto& c : data)
{
c.resize(col);
}
for (int i = 0; i < row; i ) {
for (int j = 0; j < col; j ) {
std::cin >> data[i][j];
}
}
return data;
}
int main() {
int row, col;
std::cin >> row;
std::cin >> col;
auto mydata = createMat(row, col);
// do something with it
}
CodePudding user response:
Or if you don't want to use vector, you can use pointer and do it like this.
#include<bits/stdc .h>
using namespace std;
int** createMat(int row,int col)
{
int **arr = 0;
arr = new int*[row];
for (int r = 0; r < row; r )
{
arr[r] = new int[col];
for (int c = 0; c < col; c )
{
cin>>arr[r][c];
}
}
return arr;
}
int main()
{
int row,col;
cin>>row;
cin>>col;
int** createdMat = createMat(row,col);
cout << "print Array\n";
for (int r = 0; r < row; r )
{
for (int c = 0; c < col; c )
{
printf("%i ", createdMat[r][c]);
}
printf("\n");
}
}