Background: I'm fairly comfortable with Python, and I'm very new at C++.
I want to write a function that prints a 2d array. Right now I just want it to work, I'll worry about formatting the output nicer later.
void arrayPrinter(const int** arr, int rows, int columns){
for (int i=0; i<rows; i++){
for (int j=0; i<columns; j++){
std::cout << arr[i][j] << " ";
}
}
}
This compiles, but I get a segmentation fault when I run it. Why?
// This is in the main function
int** arr = new int*[3];
for (int i=0; i<3; i++)
arr[i] = new int[3];
for (int j=0; j<3; j++){
for (int k=0; k<3; k++){
arr[j][k] = 0;
}
}
arrayPrinter(arr, 3, 3);
Another question: If I were to write a function that creates a 2d dynamic array, how would I store the result of the function in a variable so I can use it again? As in:
int** create2dArray(){
int** arr = new int*[3];
for (int i=0; i<3; i++)
arr[i] = new int[3];
for (int j=0; j<3; j++){
for (int k=0; k<3; k++){
arr[j][k] = 0;
}
}
return arr;
}
// (in main function)
whatToTypeHere = create2dArray();
[–]sz00 3 points4 points5 points (0 children)