C中的指针算术 [英] Pointer Arithmetic In C

查看:29
本文介绍了C中的指针算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段:

int (*p)[3];
int (*q)[3];

q = p;
q++;
printf("%d, %d
", q, p);
printf("%d
", q-p);

我知道指针算术是智能的,这意味着操作 q++ 提前 q 足够的字节指向下一个 3 整数数组,所以它不会令我惊讶的是,第一次打印是 '12, 0' 这意味着增加 q 使其在 12 中变大.

I know that pointer arithmetic is intelligent, meaning that the operation q++ advances q enough bytes ahead to point to a next 3-integers-array, so it does not surprises me that the first print is '12, 0' which means that incrementing q made it larger in 12.

但是第二个打印确实让我感到惊讶.它打印 1!
那么为什么它会打印 1 而不是 12 呢?这让我很困惑.

But the second print does surprises me. It prints 1!
So why would it print 1 instead of 12? it just puzzles me.

推荐答案

++ 自增运算符一样,带指针的 - 减法运算符也考虑了大小指向的对象.具体来说,返回的结果是指针值的字节数差异除以指向对象的大小(在您的示例中为 12).所以差是 12 个字节,除以大小 12,即 1.

Like the ++ increment operator, the - subtraction operator with pointers also takes into account the size of the objects being pointed to. Specifically, the result returned is the number of bytes difference in the pointer values divided by the size of the pointed-to object (12, in your example). So the difference is 12 bytes, divided by size 12, or 1.

这篇关于C中的指针算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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