0

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
redpix_
  • 701
  • 2
  • 10
  • 19
  • Well, memory is memory or isn't it? It doesn't care if it contains `double`, `int` or `char` values. – πάντα ῥεῖ Jun 07 '15 at 15:06
  • But the buffer is of type char? and doesn't it needs a cast or anything? And I'm also confused about the new usage to place it in the buffer can you explain that to me? – redpix_ Jun 07 '15 at 15:08
  • Well why I couldn't find it thanks! – redpix_ Jun 07 '15 at 15:09
  • 1
    the buffer is accessed through a double pointer. the pointer also contains a type which has been casted to double even though the buffer is ofa different type. – Alexander Oh Jun 07 '15 at 15:21

0 Answers0