| | |
Dynamic array of structures
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Apr 2008
Posts: 12
Reputation:
Solved Threads: 0
Hi all
I'm trying to create a dynamic array of structures and have come across the following code but I can't figure out how some of it works: (incidentally this is from Prata's book C++ Primer Plus, Ch4, Ex.9)
As far as I can understand - line 15
creates a pointer (Candies) which contains the address of the first element in the array (which in this case is a structure of CandyBar type)
line 18
creates a pointer (CandyPointer) which points to the address of the previous pointer when it's pointing at the first element.
Why do we need this second pointer to initialise the array elements, rather than using the first pointer?
e.g.
which I know doesn't work (syntax error) - but why not??
Thanks a lot
cobberas
I'm trying to create a dynamic array of structures and have come across the following code but I can't figure out how some of it works: (incidentally this is from Prata's book C++ Primer Plus, Ch4, Ex.9)
C++ Syntax (Toggle Plain Text)
#include <iostream> using namespace std; int main() { //structure declaration struct CandyBar { char brand[20]; float weight; int calories; }; //dynamic array declaration CandyBar *Candies = new CandyBar[3]; //create pointer to the first CandyBar structure within the array CandyBar *CandyPointer = &Candies[0]; //structure initialization one by one (*CandyPointer).brand = "Mocha Munch"; CandyPointer->weight = 2.3; CandyPointer->calories = 350; <snipped code> return 0; }
As far as I can understand - line 15
•
•
•
•
CandyBar *Candies = new CandyBar[3];
line 18
•
•
•
•
CandyBar *CandyPointer = &Candies[0];
Why do we need this second pointer to initialise the array elements, rather than using the first pointer?
e.g.
C++ Syntax (Toggle Plain Text)
CandyBar *Candies = new CandyBar[3]; Candies[0] = {"Violent Crumple", 20.5, 7000};
Thanks a lot
cobberas
when we do
CandyBar *Candies = new CandyBar[3];
we are allocating memory to hold 3 elements of CandyBar type and returning the pointer to the base address of this memory. This address will actually be same as the address of the 0th element.
both CandyPointer abd Candies point the same memory location. however for better understanding he has assigned the address of the 0th element to CandyPointer. also if he were to put this in a for loop and access each element of the array then he can use the same pointer and not lose the base address.
most importantly in C++ arrays, index starts from 0. That is the 1st element is Candies [0]
CandyBar *Candies = new CandyBar[3];
we are allocating memory to hold 3 elements of CandyBar type and returning the pointer to the base address of this memory. This address will actually be same as the address of the 0th element.
both CandyPointer abd Candies point the same memory location. however for better understanding he has assigned the address of the 0th element to CandyPointer. also if he were to put this in a for loop and access each element of the array then he can use the same pointer and not lose the base address.
most importantly in C++ arrays, index starts from 0. That is the 1st element is Candies [0]
The pointer is not needed. Perhaps this code is simply a means to demonstrate how you might access the data either via its array element or a pointer to an element. For example, lines 21-23 might also be written as:
Do you want to iterate a pointer or an index variable? You've got options.
And while we're at it, line 21 as originally written doesn't work, you can't use the assignment operator to copy to the C-style string.
C++ Syntax (Toggle Plain Text)
strcpy( Candies[0].brand , "Mocha Munch" ); //see below Candies[0].weight = 2.3; Candies[0].calories = 350;
And while we're at it, line 21 as originally written doesn't work, you can't use the assignment operator to copy to the C-style string.
"We Americans got so tired of being thought of as dumb by the rest of the world that we went to the polls last November and removed all doubt."
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
•
•
Join Date: Nov 2006
Posts: 224
Reputation:
Solved Threads: 31
•
•
•
•
which I know doesn't work (syntax error) - but why not??C++ Syntax (Toggle Plain Text)
Candies[0] = {"Violent Crumple", 20.5, 7000};
•
•
Join Date: Apr 2008
Posts: 12
Reputation:
Solved Threads: 0
That's great - thanks heaps.
That's what I thought; glad I undersdtood this correctly!
OK. Good point; I hadn't thought of that - I'm not up to that chapter of the book yet :-)
The latter, as you've shown in your sample code - thanks for that, it's exactly what I was trying to do (don't you just love novice programmers?!!)
I guess if I was wanting to access the array elements without losing the base address I'd iterate a pointer to the array rather than an index variable.
Quite so - thanks!
Cheers
Cobberas
•
•
•
•
both CandyPointer abd Candies point the same memory location
•
•
•
•
if he were to put this in a for loop and access each element of the array then he can use the same pointer and not lose the base address.
•
•
•
•
Do you want to iterate a pointer or an index variable?
I guess if I was wanting to access the array elements without losing the base address I'd iterate a pointer to the array rather than an index variable.
•
•
•
•
line 21 as originally written doesn't work, you can't use the assignment operator to copy to the C-style string.
Cheers
Cobberas
>>I think this will be possible in the next version of C++
You can do that now
Apparently you can't make Bars and array, such as Bars[3] and use initialization lists like the above. Tried it but the compiler didn't like it.
You can do that now
C++ Syntax (Toggle Plain Text)
struct CandyBar { public: CandyBar (const char* brnd, float wt, int calors) : brand(brnd), weight(wt), calories(calors) { } string brand; float weight; int calories; }; int main() { CandyBar Bars("Violent Crumple", 20.5, 7000); }
Apparently you can't make Bars and array, such as Bars[3] and use initialization lists like the above. Tried it but the compiler didn't like it.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
•
•
Join Date: Apr 2008
Posts: 12
Reputation:
Solved Threads: 0
For any other newbies out there having trouble with this exercise from Stephen Prata's book (and I've seen a few queries about this one on the 'net), here's the final solution I came up with:
There may well be more elegant ways of doing it!
Cobberas
C++ Syntax (Toggle Plain Text)
//------------------------------------------------------------------------- // Programming Exercise 4.9 //------------------------------------------------------------------------- // PREPROCESSOR directive to include contents of the iostream & string files #include <iostream> #include <string> struct CandyBar { std::string brand; float weight; int calories; }; int main(int argc, char* argv[]) { // make definitions made in the std namespace visible to the program using namespace std; //create a dynamic array of structures, & assign its address to a pointer //called 'ptrBar' //NB: ptrBar points to the 1st element of the array CandyBar * ptrBar = new CandyBar[3]; //initialise the 3 arrays using the ptrBar pointer ptrBar[0].brand = "Mocha Munch"; ptrBar[0].weight = 2.3; ptrBar[0].calories = 350; ptrBar[1].brand = "Violent Crumple"; ptrBar[1].weight = 1.5; ptrBar[1].calories = 650; ptrBar[2].brand = "Cherry Delight"; ptrBar[2].weight = 4.9; ptrBar[2].calories = 380; //display contents of each structure in the array cout << (ptrBar[0].brand).data() << " candy bar weighs " << ptrBar[0].weight << " grams and contains " << ptrBar[0].calories << " calories.\n"; cout << (ptrBar[1].brand).data() << " candy bar weighs " << ptrBar[1].weight << " grams and contains " << ptrBar[1].calories << " calories.\n"; cout << (ptrBar[2].brand).data() << " candy bar weighs " << ptrBar[2].weight << " grams and contains " << ptrBar[2].calories << " calories.\n"; cin.get(); return 0; }
There may well be more elegant ways of doing it!
Cobberas
why not just
cout << ptrBar[0].brand << //next stuff "We Americans got so tired of being thought of as dumb by the rest of the world that we went to the polls last November and removed all doubt."
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
![]() |
Other Threads in the C++ Forum
- Previous Thread: Cant understand random number generation
- Next Thread: TIC TAC TOE automized player....is me!!
| Thread Tools | Search this Thread |
api array based beginner bitmap c++ c/c++ calculator char class classes code coding compile compiler console conversion count database delete deploy desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory multiple news node number output parameter pointer problem program programming project python random read recursion recursive return sorting string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






