指针算术(char *)& a [1]-(char *)& a [0] == 4 [英] pointer arithmetic (char*) &a[1] - (char *)&a[0] == 4

查看:105
本文介绍了指针算术(char *)& a [1]-(char *)& a [0] == 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果a是一个int数组,则(char*) &a[1] - (char *)&a[0]等于4,而&a[1] - &a[0]等于1.为什么?

If a is an int array, (char*) &a[1] - (char *)&a[0] is equal to 4, while &a[1] - &a[0] is equal to 1. why is that?

推荐答案

指针数学运算所指向的数据结构的大小.这是因为如果我这样做:

Pointer math operates on the size of the data structure its pointing to. This is because if I do this:

int array[10] ;
int * p = array ;

p ++ ;

我希望p指向第二个int,而不是两个元素之间的内存.

I want p pointing at the second int, not some memory halfway in between two elements.

所以&a[1]&a[0]分开四个字节,但是询问它&a[1] - &a[0]询问分开多少个ints.当您将其转换为char时,您会要求按char的大小进行数学运算.

So &a[1] is four bytes apart from &a[0] but asking it &a[1] - &a[0] asks how many ints apart it is. When you cast it to char you ask for the math in terms of the size of char.

这篇关于指针算术(char *)& a [1]-(char *)& a [0] == 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆