指向指针等的指针算术
是否明确定义对指向指针的指针使用指针算术? 例如,
int a=some_value;
int* p=&a;
int**p2=&p;
现在对 p2 执行算术是定义明确的行为吗?(例如 p2+1、p2+2 等)
Is to well defined to use pointer arithmetic on pointers to pointers?
eg
int a=some_value;
int* p=&a;
int**p2=&p;
Now would it be well defined behavior to perform arithmetic on p2?(eg p2+1, p2+2,etc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一个答案是完全错误的:
声明一个单个指针变量(而不是指针数组)。这与带有单个元素的数组的 WRT 索引是等效的:
因此您可以执行
(&array[0]) + 1
或array + 1
或 < code>p + 1,因为允许形成一个尾后一指针:一个尾后一指针指向紧接在数组末尾之后的一个虚构元素。尾数指针不可取消引用,因为它不指向任何实际对象。但是您无法计算任何其他指针值。
特别是,
p+2
无效。The other answer is completely wrong:
declares a single pointer variable (not a array of pointers). This is equivalent, WRT indexing, with an array with a single element:
so you can do
(&array[0]) + 1
orarray + 1
, orp + 1
, because forming a one-past-the-end pointer is allowed: a one-past-the-end pointer points to an imaginary element that's just after the end of the array. The one-past-the-end pointer is not dereferenceable, because it points to no real object.But you cannot compute any other pointer value.
In particular,
p+2
is not valid.当然!
其中
p
是指针,n
是整数,总是明确定义的。它从p
本身生成“p 指向的元素类型大小的 n 倍”字节的地址。在本例中,p2
是一个指向指针的指针。因此,p2 + 4
是经过p2
的“4 * the-size-of-pointers”字节地址。由于您在特定示例中指向局部变量,因此这会很奇怪。但这不会是非法的。
Of course!
where
p
is a pointer andn
is an integer is always well-defined. It produces the address which is "n times the size of the element type p points to" bytes fromp
itself. In this casep2
is a pointer to a pointer. Sop2 + 4
is the address "4 * the-size-of-pointers" bytes pastp2
.Since you are pointing to local variables in your specific example, it would be odd. But it will not be illegal.