This is an example that was given in the book and I got confused how can array of doubles be placed in the char buffer. Why does the buffer had to be of type char? I know that we already have 512 bytes allocated but the usage confuses me.
Code:
#include <iostream>
#include <new>
const int BUF = 512;
const int N = 5;
char buffer[BUF]; // Chunk of memory
int main(){
using namespace std;
double *pd1, *pd2;
int i;
cout << "Calling new and placement new:\n";
pd1 = new double[N]; // use heap
pd2 = new (buffer) double[N]; // use buffer array but how? what?
for(i = 0; i < N; i++)
pd2[i] = pd1[i] = 1000 + 20.0 * i;
cout << "Buffer addresses:\n" << " heap: " << pd1
<< " static: " << (void *) buffer << endl;
cout << "Buffer contents:\n";
for(i = 0; i < N; i++){
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
return 0;
}
Result of the run:
Calling new and placement new:
Buffer addresses:
heap: 0x1493010 static: 0x6021a0
Buffer contents:
1000 at 0x1493010; 1000 at 0x6021a0
1020 at 0x1493018; 1020 at 0x6021a8
1040 at 0x1493020; 1040 at 0x6021b0
1060 at 0x1493028; 1060 at 0x6021b8
1080 at 0x1493030; 1080 at 0x6021c0