Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to make an array of pointers

Status
Not open for further replies.

chmilz

Programmer
Jan 10, 2001
94
0
0
CA
Hi,

I have just begun working with pointers in C++ and I am having trouble creating an array of pointers to Objects. Is there any standard that can be followed when creating them? What would the coding look like? Any help would be really hot! Thank you

Chmilz
 
Well you would get better help in the C++ forum, as this is mainly for Visual C++ (but then again...)

ok an array of pointers, hmm, well your pointers are needing to point to data you want to hold, and certainly you cant make a pointer point at two things at once.

show you a linked list, perhaps that might help.

struct node
{
int somenumber;
node *next;
}head_ptr, current_ptr;

head_ptr = current_ptr = NULL; //always initialize pointers

Node *MyNewList = New Node;

head_ptr = current_ptr = MyNewList;

now to add a guy onto him

current_ptr->next = New Node;

current_ptr = current_ptr->next;
current_ptr->next = NULL; // to set the next of the second guy to null


after a while if you mananged to create alot, lets say you'd like to find the number 10.

if (Head_ptr != NULL) //got to make sure the root pointer is not pointing to a null
{
current_ptr = head_ptr //sets current to the beginning
while (current_ptr->next != NULL)
{
if (current_ptr->somenumber == 10)
cout<<&quot;This one is the same&quot;;
current_ptr = current_ptr->next;
}
}

that'll just loop throught the entire linked list until it's next is = null, of course the problem there is that if you only have one item, and it's next is null, well you pretty much skip that guy which is why its better to do

while (current_ptr != NULL)
....

so that as soon as it does hit the end, it doesnt try to check the null value.

I am not certain about &quot;Arrays of Pointers&quot; but to me, a linked list is closest I can get to explaining it.
Karl
kb244@kb244.com
Experienced in : C++(both VC++ and Borland),VB1(dos) thru VB6, Delphi 3 pro, HTML, Visual InterDev 6(ASP(WebProgramming/Vbscript)

 
int *array_ptr[100] is an array of pointers.

Similarly -
myClass *ptr_ob[100] is an array of object pointers to the class 'myClass'.

Each element in this array is a pointer to myClass. To use the first element it would be something like..
array_ptr[o] = new myClass

Hope it helped. As again please post questions like this in the C++ forum.

Sriks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top