You are here:

C++/Multiplication Table

Advertisement


Question
I have been trying to figure out why my program won't run.  It seems to be hanging up on the Array initialization.  I hope you can help me with this, I'm going buggy! Thanks!
Russ
#include "stdafx.h"
#include "conio.h"
#include <string>

using namespace std;

int main()
{
  // 'start' and 'end' are the bounds for the array
  int start;
  int end;

  // Display text and input values
  cout << "Enter start number: ";
  cin >> start;
  cout << "Enter end number: ";
  cin >> end;
  cout << endl;
  int mt[end][10];

  if ((start < end) && (start > 0))
  {
     cout << "=============================================================" << endl;
     for (int ii = 1; ii <= 10; ii++)
     {
        cout << "|  ";
        if (ii < 10) cout << " ";
        cout << ii << " ";
     }//for
     cout << "|" << endl << "=============================================================" << endl;
  
     for (int ii = 0; ii <= end - start; ii++)
     {
        for (int jj = 1; jj <= 10; jj++)
        {
         int multiplied_val = (start + ii) * jj;
         mt[ii][jj] = multiplied_val;
         cout << "|";
         if (multiplied_val < 10) cout << " ";
         if (multiplied_val < 100) cout << " ";
         if (multiplied_val < 1000) cout << " ";
         cout << multiplied_val << " ";
        }// for
        cout << "|" << endl << "-------------------------------------------------------------" << endl;
     }// for
     return 0;
  }// if
  else
  {
     cout << "Start must be greater than 0 and start must be less than end." << endl;
     return -1;
  }//else
}//main


Answer
First sorry for not getting back to you sooner. I have been unexpectedly away from home for a few days and have only just now got access to the internet.

I am going to help with your immediate problem, that of defining the array mt. I am _not_ going to help with any further problems that might then arise once you can build your program, that is your problem <g>!

The problem is that you cannot define an array at compile time as an object allocated on the stack like this and expect the any of the dimensions to be specified at runtime. This is because the compiler is responsible for arranging for the space to be allocated and de-allocated for such objects and therefore needs the size of the array at compile time. In order to calculate the size the compiler needs:

- The type of elements in the array which gives the compiler the size of each element.
- The number of all dimensions in the array.

These two sets of items allow the compiler to calculate the size of the array in bytes (on most modern PCs). So for your case the calculation is as follows:

(byte size of single int) * rows * columns

The size of an int for a 32-bit compiler such as MSVC++ 6, 7 or 8 is 4 bytes so for an array of 10 rows of 20 columns will be 4 * 20 * 10 = 800 bytes.

As you need to specify some of the dimensions of the array at runtime you have to dynamically allocate the space for it using the C++ new [] operator and de-allocate it using delete [] when you are done, like so:

int *  array[100];

// ...

delete [] array;


However this does not work if you try to dynamically allocate a multidimensional array:

int * array new[10][20]; // DOES NOT WORK!

To work with a multidimensional array we have to modify the type of the variable we store the result of new [] and supply all bar the first dimension:

int (*array)[20] = new[10][20];

The parentheses around *array ensures the * and [] are applied to the type in the correct order. The compiler will tell you if you get it wrong.

This is good for you because this is exactly the situation you have - a 2D array in which one dimension is fixed at 10 and the other is determined at runtime. So you just have to change the definition of mt to the above format:

  int (*mt)[10] = new int[end][10];
  
And your code should compile, assuming it has no other errors. For the code you posted I removed the #include for stdafx.h and added one for iostream and the code compiled when I made the above change. The only problem now is where to de-allocate the space used for mt. Ideally you wish to do this at a common point that all code paths for which mt is defined go through such as just before returning from main:

  }//else

    delete [] mt;

}//main

But in your code this will not work as this point is unreachable as you will have returned either -1 or 0 by this point. So you might like to re-arrange your code a bit. For example, defining mt later only when you have checked start and end values is a good idea:

   if ((start < end) && (start > 0))
   {
       int (*mt)[10] = new int[end][10];

Then you only need to delete mt at the end of the if clause:

       delete []  mt;
       return 0;
  }// if

Hope this helps.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.