/* This program demonstrates * 1. Dynamic Memory * 2. Dynamic Arrays * 3. 2 dimensional dynamic arrays * * A 2 dimensional dynamic array is organized as a single dimensional array of * pointers, each of which points to a single "row" of the array - a single * dimensional array. * * This needs a 2-level pointer to access it. It also needs to be created and deleted * in 2 steps. * * We need to be sure we are within the bounds of the dynamic array. */ #include using namespace std; /* When we want to return an array from a function, the return type has to be * a pointer of the type of the array that we're returning. */ int* readDynArray(int count); int* insert(int *arr, int size, int val, int pos); /* If we have a dynamic 2D array, we use a 2-level pointer, whether * it is as a parameter or as a return type */ int ** twoDArrayDemo(int rows, int columns); int matrixSearch(int ** arr, int r, int cN, int val); int main() { int *intArr = nullptr; int size; cout<<"Enter the number of elements: "; cin>>size; intArr = readDynArray(size); cout<<"\nPrinting from main: \n"; for(int i=0; i>num; cout<<"Enter the position: "; cin>>pos; // Call the insert function and then store the returned array in the same pointer intArr = insert(intArr,size,num,pos); size++; // we have 1 more element cout<<"\nArray after insert:\n"; for(int i=0; i>r>>c; // We need a 2-level pointer to point to a 2D dynamic array int ** mat = twoDArrayDemo(r,c); cout<<"The matrix is : \n"; for(int i=0; i>searchCol; cout<<"Enter the value to search: "; cin>>val; int found = matrixSearch(mat,r,searchCol,val); cout<<"Value was found in row "<< found; // delete the 2D array // first, delete each individual row for(int i=0; i>array[i]; cout<<"Printing from the function:\n"; for(int i=0; i> mat[i][j]; } /* The max norm of a matrix is the largest balue in th ematrix */ int maxNorm = mat[0][0]; for(int i=0; i maxNorm) maxNorm = mat[i][j]; } } cout<<"The max norm is "<< maxNorm<