为什么const指针中的结构操作是非法的

Why illegal structure operation in const pointer?

本文关键字:操作 非法 结构 为什么 指针 const      更新时间:2023-10-16

为什么我必须在cout子句中添加&,而使用const指针。我在下面的代码中。如果我不加&子句,它就是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)
}


我希望我的输出是这样的:stdout:

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

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

否则,您将从pMarks + i传递地址