Click to See Complete Forum and Search --> : Dynamic Allocation problem with lists


armen_shlang
June 3rd, 2008, 07:01 PM
I have something like this:


#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

struct boy
{
int age;
string name;
};

void main()
{
typedef boy* botPtr;

botPtr * As[6000];
for( int i = 0 ; i < 6000 ; i++)
As[i] = new botPtr;

botPtr * Ps = new botPtr[2000];

Ps[0]->age;
As[0]->age //produces an error
}


How can i access the As[0] data structure elements

Duoas
June 3rd, 2008, 07:35 PM
I think you goofed when you declared As, since it is an array of 6000 pointers to (pointer to boy).

Then the second line below that you dynamically allocate a pointer for each element of As[].

Are you sure you don't want:

typedef boy* botPtr;

botPtr As[6000]; // 6000 pointers to boy

for (int i = 0; i< 6000; i++) // create 6000 boys
As[i] = new boy;

As[0]->age = 12;

?

[edit]
BTW, it is typically a dangerous kind of thing to typedef a pointer so you can get rid of that *. Doing so just causes these kinds of errors and confuses other programmers. If you want a pointer to a boy, just use boy*.

boy* As[6000];

Hope this helps.

TheCPUWizard
June 3rd, 2008, 07:54 PM
An even bigger question is why not use an STL container...since it is apparent you are ALREADY using STL????


using namespace std;

struct boy
{
int age;
string name;
};

std::vector<boy> myVar; // No need to wory about memory at alll...

std::vector<boy *> myVar; // poor...need to worry about memory...

struct boyptr
{
boyptr() { realBoy = new boy(); }
~boyptr() { delete realboy; }
boy *realboy; // NOT Pinochio.
}

dtd::vector<boyptr> myVar; // No memory management, yet still allows ptr type assignments....

Duoas
June 3rd, 2008, 08:07 PM
:-D

Good point. Don't forget to #include <string>.