Hello. I'm working on an exercise problem from C++ Primer Plus. What I am supposed to do is place an array of structures into a buffer and then initialize the structure members. When I tried this initially, I found that the input from my first structure would be overwritten by the values assigned to the second structure. I noticed that this did not happen though when I used the code in the title to place the second array. What I am not sure of is whether this is forcing the 2nd structure to exceed the bounds of the buffer or if this is essentially placing the 2nd structure in buffer[50] of the buffer array? Thanks for your assistance.
//Exercise3 -- Write a program that uses placement new to
//place an array of two such structures in a buffer. Then
//assign values to the structure members (remembering to use
//strcpy() for the char array) and use a loop to display the
//contents. Option 1 is to use a static array, like that in
//Listing 9.9, for the buffer. Option 2 is to use regular new
//to allocate the buffer.
#include <iostream>
#include <new>
struct chaff
{
char dross[20];
int slag;
};
void assignChaff(chaff & c);
void showChaff(const chaff & c);
int main()
{
//Create buffer
char buffer[100];
//Create array of structures
chaff * chaffArray[2];
//place structures in the buffer
chaffArray[0] = new (buffer) chaff;
chaffArray[1] = new (buffer + 50) chaff;
//Call function allowing users to initialize structures
assignChaff(*chaffArray[0]);
assignChaff(*chaffArray[1]);
//show member data in structures
for (int i = 0; i < 2; i++)
showChaff(*chaffArray[i]);
//delete memory created by new
delete [] *chaffArray;
}
void assignChaff(chaff & c)
{
using std::cin;
using std::cout;
using std::endl;
cout << "Enter your first name: ";
while (!(cin.getline(c.dross, 20)))
{
cout << "\nBad input. Enter a name: ";
cin.clear();
while (cin.get() != '\n')
continue;
}
cout << "\nEnter your age: ";
while (!(cin >> c.slag))
{
cout << "\nBad Input. Enter an age: ";
cin.clear();
while (cin.get() != '\n')
continue;
}
if (cin.get() == '\n')
cin.clear();
cout << endl;
}
void showChaff(const chaff & c)
{
using std::cout;
using std::endl;
cout << "\nName: " << c.dross << endl
<< "Age: " << c.slag << endl;
}
So does the lack of responses mean that no one knows? Or that the answer is so obvious I should be able to figure it out myself? I'm just trying to verify if adding + 50 to the buffer in a placement new implementation is valid or if it is a bad work around. Thanks.
Well if you read the comments above the code you see that the exercise problem requires me to use placement new to dynamically store data instead of regular new. The difference is that while regular new create space dynamically at a random address, placement new allows me to dynamically store data at an address that has already been declared, which is char buffer[100] in this context. My problem is determining whether (buffer + 50) is the same as storing chaffArray[1] @ buffer[49] instead of buffer[0].