在C中,指针和数组之间的算术如何工作?

时间:2012-10-23 12:27:29

标签: c pointers

y的价值应该是什么?为什么?

int x[] = { 1, 4, 8, 5, 1, 4 }; 
int *ptr, y; 
ptr  = x + 4; 
y = ptr - x;  

我认为y应该是4 * sizeof(int),但是它给出了4.为什么?

4 个答案:

答案 0 :(得分:8)

I think y should be 4*sizeof(int)

好好思考,猜猜怎么着? 给予4*sizeof(int),但您没有正确看待它。 ;)

当你玩指针时,你正在查看地址,所以让我们查看一些地址

int x[] = { 1, 4, 8, 5, 1, 4 };

//Just for fun, what is the address of each element in the array?
printf("%#x, %#x, %#x, %#x, %#x, %#x\n", x+0, x+1, x+2, x+3, x+4, x+5);

ptr = x + 4;

printf("%#x - %#x\n", ptr, x);  // Give us the address of ptr in hex
                                // and give us the address of x
y = ptr - x;                    

printf("%d\n", y);

输出:

   x[0]         x[1]        x[2]        x[3]         x[4]       x[5]
0xbf871d20, 0xbf871d24, 0xbf871d28, 0xbf871d2c, 0xbf871d30, 0xbf871d34

   ptr           x
0xbf871d30 - 0xbf871d20

4

所以ptr是x+4(在你的情况下真的是x + 4*sizeof(int)x+16)。我们将从x或基地址中减去,因此实际数学为0x30 - 0x20 = 0x10或以16为单位。

您在输出中看到4的原因是因为编译器知道您正在对int *进行操作,所以它将16除以sizeof(int)为您。好的嗯?

如果你想看到实际值,你需要做这样的事情:

int one, two;
...
one = (int)ptr;  //get the addresses, ignore the "type" of the pointer 
two = (int)x;
y = one - two;

现在y会给你0x10(十六进制)或16(十进制)

答案 1 :(得分:7)

它应该是指向x的开头的地址与x的第4个元素的地址=>之间的int数。 4。

来自c99标准:

  

6.5.6加法运算符

     

9 /当减去两个指针时,两个指针都指向   相同的数组对象,或者超过数组最后一个元素的数组   宾语;结果是两者下标的差异   数组元素。

要了解更多信息,请尝试搜索指针算术

答案 2 :(得分:4)

只需应用一些简单的代数

if
    ptr = x + 4
and
    y = ptr - x

therefore

y = (x + 4) - x

hence y = 4 + x - x

thus y = 4 + 0 

     y = 4

编辑:处理评论

这是C,ptr只是任何大小位的值。向它添加一个数字(溢出的情况除外)只是一些整数+另一个整数(转换为适当的大小),因此删除原始数字会留下余数。由于我们只添加了4(小于int),这意味着没有任何问题隐式将其转换为y int。

答案 3 :(得分:2)

如果二进制的操作数' - '
 是两个相同类型的指针,它被评估为

  

(p-q)/ sizeof(p或q的类型)

如果第二个操作数是整数
 那么

  

p - sizeof(p)* q