Well, explaining that is very easy.
double* ptr;
is just a pointer that points to somewhere in memory. It holds a garbage value of a pointer, just like when you say
int i;
contains a garbage value till you initialise it.
Now, if you write:
ptr = new double;
, you're telling the pointer that I allocated some memory for a double, and I want you to point to that location. That creates a single slot for a single double.
For
ptr = new double[N]
, you're allocating space for N doubles, and the pointer will point to the first element. A rule in C++ is, every array is a pointer, but not every pointer is an array; in other words, you can always represent an array with a pointer. Now to access the elements of ptr, you can dereference in 2 ways:
1 2
|
ptr[5] = 10.2; //dereference as an array, you're accessing the 6th element
*(ptr+5) = 10.2; //you're moving your pointers by 5 locations, and then accessing the element, which is equally like dereferencing by [] operator.
|
Now in my code, you're allocating an array of pointers (with size STUDENTS), and each pointer in that array points to an array with size TESTS.
So the program allocates at the beginning STUDENTS elements, and then goes into each element of that array an allocates TESTS elements.
----------------
If you find this hard to understand, and since you came from a very easy language, Java, you may use C++ std containers. They're dynamic and change their size dynamically when you add elements to them. As a start, use vectors. You can get the same result from vectors as in my previous code as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <vector>
using namespace std;
int main()
{
vector< vector<double> > scores; //notice the spacebar between the last 2 > symbols
scores.resize(STUDENTS);
for(unsigned long i = 0; i < scores.size(); i++)
{
scores[i].resize(TESTS);
}
// now scores is a 2D array, you can access it with [] operator (you can't dereference it like pointers, because it's an object).
}
|
That's way easier, isn't it? read more about vectors here:
www.cplusplus.com/reference/stl/vector/
Cheers :)