954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

array of structs

I have a struct. I want to declare a pointer to that struct. Now I want 10 of those structs. How is this declared? I have tried (call the struct foo for example):

foo* test[10];

when I make a call to test[0]->whatever or test[5]->whatever it seems to always write to the first element (the 0th of the array).

I think what I'm getting is an array of pointers. I want a pointer to an array of structs.

How do I delare this? Thanks.

Nemoticchigga
Junior Poster in Training
98 posts since Feb 2008
Reputation Points: 10
Solved Threads: 2
 

Yes, you are getting an array of pointers.

Instead, declare your array of structs:
foo test[10];

Now you have 10 foo objects and foo[0].myMember will reference the contents of the first one.

To get a pointer you then use:
foo* pFoo = &test[0];
which will give you a pointer to the first one.

MrSpigot
Junior Poster
158 posts since Mar 2009
Reputation Points: 76
Solved Threads: 40
 

Correction: you are getting an array of uninitialized pointers. Accessing them may result in undefined behaviour. So do it like MrSpigot recommends or use new to initialize the array members.

jencas
Posting Whiz
366 posts since Dec 2007
Reputation Points: 395
Solved Threads: 71
 

you can also do it like Jenca's second suggestion like:

foo *test;
foo = new struct foo[10];
SeeTheLite
Junior Poster
109 posts since Mar 2009
Reputation Points: 38
Solved Threads: 13
 

Thanks all.

MrSpigot, how would I then access the structs through the pointer?

pFoo->test[0].index = blah; does not work. How would this be done?

Thanks.

Nemoticchigga
Junior Poster in Training
98 posts since Feb 2008
Reputation Points: 10
Solved Threads: 2
 

Thanks all.

MrSpigot, how would I then access the structs through the pointer?

pFoo->test[0].index = blah; does not work. How would this be done?

Thanks.


pFoo->index = blah;
will access the first struct, but more generally you could use pFoo[n].index = blah;

Or modify pFoo:
pFoo += 1;
pFoo->index = blah; // pFoo now references the second struct

MrSpigot
Junior Poster
158 posts since Mar 2009
Reputation Points: 76
Solved Threads: 40
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You