C ++指针偏移量得到平方

时间:2017-11-02 01:38:18

标签: c++ pointers offset

我有一个名为' tod'的数据类型,我使用它创建数组。要在函数内部(使用指针)迭代此类型的元素,我想使用偏移量。但是,此偏移在操作期间变为平方:

tod theTime[] = { {12,0,0, "noon"}, {0,0,0, "midnight"}, {11,30,0, "lunch time"}, {18,45,0, "supper time"}, {23,59,59, "bed time"} };
auto tsize = sizeof(tod);
auto p1 = &theTime[0];
auto p2 = &theTime[0] + tsize;
cout << "size of tod = " << tsize << endl;
cout << "p1 = " << p1 << endl;
cout << "p2 = " << p2 << endl;

这让我:

size of tod = 44
p1 = 0x7ffd3e3b0bf0
p2 = 0x7ffd3e3b1380

两个十六进制值之间的差异降至0x790,即1936(十进制)和44 ^ 2。这是怎么回事?有人请帮忙。

1 个答案:

答案 0 :(得分:3)

您对pointer arithmetic

的误解
  

如果指针P指向数组的第i个元素,则表达式P + n,n + P和Pn是指向i + nth,i + nth和i-的相同类型的指针。分别是同一个数组的第n个元素。

e.g。 &theTime[0] + 1将返回指向数组theTime的第二个元素的指针;然后&theTime[0] + tsize将尝试返回指向tsize + 1元素的指针(注意它已离开边界并通向UB)。这就是你获得1936的原因,即44 * 44

相关问题