递增指针(ptr ++)和(* ptr ++) [英] Incrementing pointer (ptr++) and (*ptr++)

查看:176
本文介绍了递增指针(ptr ++)和(* ptr ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有这个疑问时,我正在重新探寻指针.

I was revisiting pointers when I had this doubt.

int *ptr;
int arr[5] = {10,20,30,40,50};
ptr = &arr[0];

现在printf("Value: %d",*ptr);将打印10

如果我这样做:

ptr++;
printf("Value: %d",*ptr);

结果将是:20

类似地,如果我这样做:

Similarly if I do:

*ptr++;
printf("Value: %d",*ptr);

结果是:30

但是

printf("Value: %d",++*ptr);

给我31

我认为由于ptrint类型,所以当我增加它时,它将跳4个字节到下一个内存位置.但是,为什么对于*ptr++ptr++却显示相同的行为,而对于++*ptr却没有?

I thought since ptr is of type int when I increment it, it would jump 4 bytes to the next memory location. But why does it show the same behavior for *ptr++ and ptr++ and not for ++*ptr?

推荐答案

第一个摘要很明显:它打印ptr指向的内容,即10.

The first snippet is obvious: it prints what ptr points to, i.e. 10.

第二个,将指针向前移动一个元素,然后指向下一个元素,即20.

The second one, moves the pointer forward of one element, which then points to the next element, i.e. 20.

第三个代码段与前一个代码段完全相同,因为它的第一个指令递增指针并返回未递增的值,该值被取消引用,但其结果被丢弃; printf中取消引用的是递增的指针,该指针现在指向30.

The third snippet is exactly the same as the previous one, because its first instruction increments the pointer and returns the unincremented value, which is dereferenced, but its result is discarded; what is dereferenced in the printf is the incremented pointer, which now points to 30.

最后一个代码段是不同的:++*ptr++(*ptr); *ptr取消引用ptr(已经指向30),产生30,并且++将该值递增,变为31.

The last snippet is different: ++*ptr is ++(*ptr); *ptr dereferences ptr (which already points to 30), yielding 30, and ++ increments such value, which becomes 31.

这篇关于递增指针(ptr ++)和(* ptr ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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