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)
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:
both CandyPointer abd Candies point the same memory location
That's what I thought; glad I undersdtood this correctly!
Quote ...
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.
OK. Good point; I hadn't thought of that - I'm not up to that chapter of the book yet :-)
Quote ...
Do you want to iterate a pointer or an index variable?
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.
Quote ...
line 21 as originally written doesn't work, you can't use the assignment operator to copy to the C-style string.
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:
Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.
This thread is more than three months old
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.