|
-
June 3rd, 2008, 07:01 PM
#1
Dynamic Allocation problem with lists
I have something like this:
Code:
#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
Last edited by armen_shlang; June 3rd, 2008 at 07:11 PM.
-
June 3rd, 2008, 07:35 PM
#2
Re: Dynamic Allocation problem with lists
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:
Code:
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*.
Hope this helps.
Last edited by Duoas; June 3rd, 2008 at 07:37 PM.
-
June 3rd, 2008, 07:54 PM
#3
Re: Dynamic Allocation problem with lists
An even bigger question is why not use an STL container...since it is apparent you are ALREADY using STL????
Code:
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....
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
June 3rd, 2008, 08:07 PM
#4
Re: Dynamic Allocation problem with lists
:-D
Good point. Don't forget to #include <string>.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|