为什么在使用&
指针时必须在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)
}
我希望我的输出会是这样的:
标准输出:
的
元素0:0x7fff1d26d6c0 + 0字节= 0x7fff1d26d6c0
元素1:0x7fff1d26d6c0 + 4字节= 0x7fff1d26d6c4
元素2:0x7fff1d26d6c0 + 8字节= 0x7fff1d26d6c8
元素3:0x7fff1d26d6c0 + 12字节= 0x7fff1d26d6cc
元素4:0x7fff1d26d6c0 + 16字节= 0x7fff1d26d6d0
元素5:0x7fff1d26d6c0 + 20字节= 0x7fff1d26d6d4
元素6:0x7fff1d26d6c0 + 24字节= 0x7fff1d26d6d8
元素7:0x7fff1d26d6c0 + 28字节= 0x7fff1d26d6dc
元素8:0x7fff1d26d6c0 + 32字节= 0x7fff1d26d6e0
答案 0 :(得分:1)
怎么样?
cout << bytes << " bytes" << " = " <<*(pMarks + i) << endl;
否则您将从pMarks + i
传递地址。