drdot
drdot

Reputation: 3347

Cannot print buffer address

I want to test the following code, however I get a compilation error. The thing that confuse me is that the way and create and print pd1 and pd2 are the same as pd3 and pd4, but the compiler complains about pd3 and pd4 when I print.

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
    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;
    }

    cout << "\nCalling new and placement new a second time:\n";
    double *pd3, *pd4;
    pd3 = new double[N];
    pd4 = new (buffer) double[N];
    for(i = 0; i < N; i++) 
        pd4[i] = pd3[i] = 1000 + 20.0 * i;
    cout << "Buffer contents:\n";
    for (i = 0; i < N; i++) {
        cout << pd3[i] < " at " << &pd3[i] << "; ";
        cout << pd4[i] < " at " << &pd4[i] << endl;
    }

    return 0;
}

Compilation error:

newplace.cpp: In function ‘int main()’:
newplace.cpp:33:36: error: invalid operands of types ‘const char [5]’ and ‘double*’ to binary ‘operator<<’
   cout << pd3[i] < " at " << &pd3[i] << "; ";
                                    ^
newplace.cpp:34:36: error: invalid operands of types ‘const char [5]’ and ‘double*’ to binary ‘operator<<’
   cout << pd4[i] < " at " << &pd4[i] << endl;

Upvotes: 0

Views: 112

Answers (2)

Greg M
Greg M

Reputation: 954

You only put one < in the stream where you are trying to print out the buffer contents.

cout << pd3[i] < " at " << &pd3[i] << "; "; // there is only one <
cout << pd4[i] < " at " << &pd4[i] << endl; // ^

Make sure you have two <'s in the stream insertion operator.

cout << pd3[i] << " at " << &pd3[i] << "; ";
cout << pd4[i] << " at " << &pd4[i] << endl;

Upvotes: 1

kvorobiev
kvorobiev

Reputation: 5070

You missing one < symbol here

 cout << pd3[i] < " at " << &pd3[i] << "; ";
 cout << pd4[i] < " at " << &pd4[i] << endl;

Try

 cout << pd3[i] << " at " << &pd3[i] << "; ";
 cout << pd4[i] << " at " << &pd4[i] << endl;

Upvotes: 2

Related Questions