I am a newbie in C++ programming and trying to learn the language from reading an Ebook called Jumping into C++ by Alex Allain, and I have currently finished the dynamic memory allocation chapter and I must say that I find pointers difficult to understand.
At the end of the chapter is a series of practice problem I can try out, I have completed the first problem (took me a while to get my code working) which is to write a function that builds the multiplication table of arbitrary dimensions (you have to use pointers for the problem), but I am not satisfied with my solution if it’s correct and if I am using the pointers the right way, I want someone who has experience to point out the flaws, if there are, below is my own solution to the problem:
// pointerName.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <string>
void multTable(int size){
int ** x, result;
x = new int*[size]; // lets declare a pointer that will point to another pointer :).
result = 0;
for(int h = 0; h < size; h++){ // lets store the address of an array of integers.
x[h] = new int [size];
}
std::cout << std::endl << "*********************************" << std::endl; // lets seperate.
for(int i=0; i < size+1; i++){ // lets use the pointer like a two-dimensional array.
for(int j=0; j < size+1; j++){
result = i*j; // lets multiply the variables initialized from the for loop.
**x = result; // lets inialize the table.
std::cout << **x << "\t"; // dereference it and print out the whole table.
}
std::cout << std::endl;
}
/************* DEALLOCATE THE MEMORY SPACE ************/
for(int index = 0; index < size; index++){
delete [] x[index]; // free each row first.
}
delete [] x; // free the pointer itself.
}
int main(int argc, char* argv[]){
int num;
std::cout << "Please Enter a valid number: ";
std::cin >> num; // Lets prompt the user for a number.
multTable(num);
return 0;
}
What billz said and also **x must change to x[i][j]. Since you seem new it would be good practice to print the multiplication table as a seperate block (outside the two for loops).