# Two-dimensional arrays on the free store

This lesson contains approximately

**25 minutes**of video content.### Discussion on pointers

### Two dimensional array on the free store

### Passing two-dimensional arrays to functions

#### Activity: Two-dimensional arrays on the free store

Graded Playground Autograder

**Activity Prompt:**

In this activity, you are given a 1D array of length x*y, and you will take its values and store them in a 2D array of dimensions (x, y). You will also implement some methods that work with the 2D array.

###### Function Signatures and Behaviors

`int** Empty2dArray(unsigned int num_rows, unsigned int num_cols)`

Creates an empty 2D array of dimensions height: num_rows and width: num_cols on the free store, initializes each int object in the array with 0, then returns the pointer to the array.`void Init2dArray(int src[], int** dest, unsigned int num_rows, unsigned int num_cols)`

Takes in an array as the source array, and a pointer to an integer pointer as the destination array, along with positive integers x and y specifying the dimensions that destination should be.`src`

is a 1-dimensional array of size x*y, while`dest`

points to a 2D array of size (x, y).`dest`

is a valid pointer to a two-dimensional array allocated on the free store; this function should not allocate additional dynamic memory.

For example, running`Init2dArray(src, dest, 2, 3)`

, where src looks like1 2 3 4 5 6 1 2 3 4 5 6 `void Print2dArray(int** arr, unsigned num_rows, unsigned num_cols, std::ostream& os = std::cout)`

Prints arr to the stream specified (with a default of`std::cout`

). Elements on the same row should be separated by spaces, and rows should be separated by line breaks. Do not insert a space after the last element in a row and do not insert a line feed after the last row of data. Recall how you overloaded the insertion operator, which may help.

#include <iostream>
#include "twodarray.hpp"
int main(){
const int x = 4, y = 5;
int **arr = Empty2dArray(x,y);
int onedarray[] = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21};
Print2dArray(arr, x, y);
Init2dArray(onedarray, arr, x, y);
Print2dArray(arr, x, y);
return 0;
}

#include "twodarray.hpp"
int** Empty2dArray(unsigned int num_rows, unsigned int num_cols) {
//Your code here
}
void Init2dArray(int src[], int** dest, unsigned int num_rows, unsigned int num_cols) {
//Your code here
}
void Print2dArray(int** arr, unsigned num_rows, unsigned num_cols, std::ostream& os) {
//Your code here
}

#ifndef TWODARRAY_HPP
#define TWODARRAY_HPP
#include <iostream>
int** Empty2dArray(unsigned int num_rows, unsigned int num_cols);
void Init2dArray(int src[], int** dest, unsigned int num_rows, unsigned int num_cols);
void Print2dArray(int** arr, unsigned num_rows, unsigned num_cols, std::ostream& os = std::cout);
#endif

Submit is not supported in this site.