![]() |
| ||
| Dynamic array of structures 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) #include <iostream> As far as I can understand - line 15 Quote:
line 18 Quote:
Why do we need this second pointer to initialise the array elements, rather than using the first pointer? e.g. CandyBar *Candies = new CandyBar[3];which I know doesn't work (syntax error) - but why not?? Thanks a lot cobberas |
| ||
| Re: Dynamic array of structures 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] |
| ||
| Re: Dynamic array of structures 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: strcpy( Candies[0].brand , "Mocha Munch" ); //see belowDo 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. |
| ||
| Re: Dynamic array of structures Quote:
|
| ||||
| Re: Dynamic array of structures That's great - thanks heaps. Quote:
Quote:
Quote:
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. Quote:
Cheers Cobberas |
| ||
| Re: Dynamic array of structures >>I think this will be possible in the next version of C++ You can do that now struct CandyBar 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. |
| ||
| Re: Dynamic array of structures 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 |
| ||
| Re: Dynamic array of structures why not just cout << ptrBar[0].brand << //next stuff |
| All times are GMT -4. The time now is 3:15 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC