Hello, I have to create am int value in main function, pass it to Data function, and make it a 2D array there, but I have no idea how to pass normal int value and when done, how to pass 2D array to Pass function. Here I have a simple array. but how do I make it work with 2D ?
Elements in 2D array are still allocated next to each other like in this case
1 2 3 4 5 6 7 8 9
If you pass only pointer to 1st element to your 2D array you cant use it as 2D array anymore inside the function you passed it to, only as 1D. But as you see in this example it wont stop you from printing this 1D array in function f(int*, int dim1, int dim2) as if it was 2D array.
Thank you for your answer. I have to pass a normal variable to Data function, and only there to make it as a 2D array, but im unsure how to do it. I will also get arrays size in Data function.
#include <iostream>
#include <fstream>
usingnamespace std;
int Data(int** Books)
{
int row, col;
ifstream ifile("data.txt");
ifile >> row >> col;
Books = newint*[row ];
for(int i = 0; i < row ; ++i)
Books [i] = newint[col];
return row;
}
void Pass(int** Books)
{
//do some stuff with them
}
void deallocate(int** Books, int row)
{
for(int i = 0; i < row ; ++i)
delete[] Books[i];
delete[] Books;
}
int main()
{
int** Books; //A dynamic 2D array is basically an array of pointers to arrays
int rows = Data(Books);
Pass(Books);
deallocate(Books, rows); //figure out how to get dimension sizes outside of Data
return 0;
}
I havent checked out if this actually works but this would be my quess. I think you cant just delete[] Books if its array of arrays but I havent done this so I might be wrong
EDIT : looks like there be something wrong with both deallocate function and using Books like this Books[3][3] = 4;
Im getting
Segmentation fault (core dumped)
compiling this is some places
EDIT2 :D found the problem, had to pass int** by reference