I did a little problem to practice with pointers to other pointers. In this case, I did a matrix and pass it by a function than expect the reference of it.
The example compute the multiplication of two matrices.
Note: This post was inspired answering that post: http://www.cplusplus.com/forum/general/86553/
Enjoy it:
#include <iostream> #include <algorithm> #include <stdlib.h> using namespace std; void fill(int& value){ static int val = 0; val++; value = val; } void zero(int& value){ value = 0; } void mult(int* **A,int* **B,int* **result, const int SIZE) { for (int i = 0; i < SIZE; i++) for (int j = 0; j < SIZE; j++) for (int k = 0; k < SIZE; k++) (*result)[i][j] += B[0][i][k] * (*A)[k][j]; } int main(){ int *vector; const int SIZE = 3; //reserve memory: vector = (int*) malloc(sizeof(int) * SIZE); for_each(vector,vector + SIZE,fill); //fill //print for(int i = 0 ; i < SIZE ; i++) cout << vector[i] << ", "; cout << endl << endl << endl; //reserve memory for a pair of matrices: int**matrix; matrix = (int**) malloc(sizeof(int*) * SIZE ); for(int i = 0 ; i < SIZE ; i++ ) matrix[i] = (int*) malloc(sizeof(int) * SIZE); int**result; result = (int**) malloc(sizeof(int*) * SIZE ); for(int i = 0 ; i < SIZE ; i++ ) result[i] = (int*) malloc(sizeof(int) * SIZE); //*************************** //fill matrix: for_each(matrix[0],matrix[0] + SIZE,fill); for_each(result[0],result[0] + SIZE,zero); for_each(matrix[1],matrix[1] + SIZE,fill); for_each(result[1],result[1] + SIZE,zero); for_each(matrix[2],matrix[2] + SIZE,fill); for_each(result[2],result[2] + SIZE,zero); //print it for(int i = 0 ; i < SIZE ; i++){ for(int j = 0 ; j < SIZE ; j++) cout << matrix[i][j] << ", "; cout << endl; } cout << endl << endl << endl; mult(&matrix, &matrix, &result, SIZE); //print it for(int i = 0 ; i < SIZE ; i++){ for(int j = 0 ; j < SIZE ; j++) cout << result[i][j] << ", "; cout << endl; } cout << endl << endl << endl; system("pause"); return 0; }