指针运算在C [英] Pointer Arithmetic In C

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

问题描述

考虑以下code片段:

Consider the following code fragment:

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

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

我知道,指针运算是智能的,这意味着未来的操作①++ 进步足够的字节为指向下一个三整数数组,所以它不会令我感到奇怪的第一次印刷是 12,0 这意味着递增问:使其成为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天全站免登陆