ok so it seems like you're just starting to step into the wonderful world of pointers. Welcome, it only gets better from here.
The first thing you need to always remember is that where there is a * (pointer) there needs to be a
new
and
delete
accompanying that pointer.
In regards to your last question the reason the first value contains of a contains memory is because you've only declared a single pointer, not an array. So everything there after is garbage. Also, you're dereferencing the pointer to object level and making an assignment. If you were not dereferencing ( (*a) ) I'm pretty sure you will get an error thrown.
Keep in mind that the ' . ' operator is accessing variables as an object and ' -> ' is accessing information from a pointer (dynamic memory)
Here's a complete example that will work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
using namespace std;
class MyClass{
public:
MyClass() {}
int nValue;
};
int main()
{
int size;
cout << "Size of array: " << endl;
cin >> size;
MyClass **MyClassList;
MyClassList = new MyClass*[size];
for(int i = 0; i < size; i++)
{
MyClassList[i] = new MyClass();
MyClassList[i]->nValue = i;
}
for(int i = 0; i < size; i++)
{
cout << MyClassList[i]->nValue << endl;
}
system("pause");
delete[] MyClassList;
return 0;
}
|
You really need to be aware that having an array of pointers is allocated like in my above example. If you do not have the double ** it is simply just a dynamic array of objects.
No leaks were reported after running this example.
@Shinigami
Good!
P.S.S but this code creates a memory leak. At the end you need to use.
delete[] pMC[0];
delete[] pMC[1];
delete[] pMC[2];
delete[] pMC[3];
delete[] pMC[4]; |
You're mixing two different things there. delete[] delete dynamic pointer arrays. So the correct syntax for clearing the memory to prevent a leak would be:
What you're demonstrating is more along the lines of individually deleteing each index of memory allocation. So you're solution is more like this:
1 2 3 4 5
|
delete pMC[0];
delete pMC[1];
delete pMC[2];
delete pMC[3];
delete pMC[4];
|
References:
Experience
http://www.cplusplus.com/forum/general/20044/
http://www.cplusplus.com/doc/tutorial/dynamic/