Ravi Parkash
Ravi Parkash

Reputation: 3

Why illegal structure operation in const pointer?

Why do I have to add & in cout clause while using const pointer. I'm in the code below. And if I don't add & clause it says illegal structure operation.

int Marks [10]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
// Create a constant pointer to Marks array
const int* pMarks = Marks;
for (int i = 0, bytes = 0; i < 10; ++i, bytes += 4)
{
  cout <<  "Element " << i << ": " << pMarks <<" + ";
  cout <<  bytes << " bytes" << " = " << (pMarks + i) << endl; // that & is required before (pMarks + i)
}


I want my output would be something like this: stdout:

Element 0: 0x7fff1d26d6c0 + 0 bytes = 0x7fff1d26d6c0
Element 1: 0x7fff1d26d6c0 + 4 bytes = 0x7fff1d26d6c4
Element 2: 0x7fff1d26d6c0 + 8 bytes = 0x7fff1d26d6c8
Element 3: 0x7fff1d26d6c0 + 12 bytes = 0x7fff1d26d6cc
Element 4: 0x7fff1d26d6c0 + 16 bytes = 0x7fff1d26d6d0
Element 5: 0x7fff1d26d6c0 + 20 bytes = 0x7fff1d26d6d4
Element 6: 0x7fff1d26d6c0 + 24 bytes = 0x7fff1d26d6d8
Element 7: 0x7fff1d26d6c0 + 28 bytes = 0x7fff1d26d6dc
Element 8: 0x7fff1d26d6c0 + 32 bytes = 0x7fff1d26d6e0

Upvotes: 0

Views: 1502

Answers (1)

bash.d
bash.d

Reputation: 13207

What about

cout <<  bytes << " bytes" << " = " <<*(pMarks + i) << endl;

Otherwise you would be passing the address from pMarks + i.

Upvotes: 1

Related Questions