C-具有前后增量的指针行为 [英] C - pointer behavior with pre and post increment

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

问题描述

我正在用C指针做一些实验,试图理解它的行为.以下是我对以下代码的假设.如果我错了,请纠正我. 我有以下代码:

In am doing some experiment in C pointers and trying to understand its behaviour. The following are my assumptions for the below codes. Correct me if I am wrong. I have the following codes:

int n[5] = {3,6,9,12,15};   
int *ptr = n;
ptr++;

printf("%d", *ptr);  //Needless to say, the output will be 6

我的假设:上面的输出为6,因为ptr++表示ptr = ptr + 1我正在更改ptr的,即地址n[0].

My assumption: The output above is 6 because ptr++ means ptr = ptr + 1 I am changing the value of ptr which is the address of n[0].

现在,我们来看看以下情形:

Now we take a look at the following scenario:

int n[5] = {3,6,9,12,15};   
int *ptr = n;
*ptr++;

printf("%d", *ptr);  //Why is the output still 6?

我的问题是:我们如何解释*ptr++?这是否意味着:

My question is: How do we interpret *ptr++? Does it means:

  • * ptr = * ptr +1或
  • * ptr = ptr + 1或
  • ptr = ptr + 1或什么?

顺便说一句,当我打印出n的值时,它仍然是3,6,9,12,15.

By the way, when I print out values of n, it is still 3,6,9,12,15.

对不起,第二个问题:

那我们该如何解释*++ptr++*ptr?

推荐答案

表达式

*ptr++;

具有价值

*ptr

在递增ptr之前,然后ptr本身就是递增.没有写意

before incrementing ptr and then ptr is increment itself. There is no sense to write

*ptr++;

因为未使用在ptr递增之前的*ptr表达式值.所以实际上这些表达式(表达式语句)的结果

because the value of expression that is *ptr before incrementing of ptr is not used. So in fact the result of these expressions (expression-statements)

ptr++;

*ptr++;

是相同的.

对于表达式*++ptr++*ptr,则在此表达式中,第一个ptr的* ++ ptr递增(即它将指向数组的第二个元素),然后被取消引用,其值是第二个要素. 在此表达式++*ptr中,首先返回数组的第一个元素的值(即3),然后将该值递增,您将得到4.

As for expressions *++ptr and ++*ptr then in this expression *++ptr at first ptr is incremented ( that is it will point to the second element of the array) and then dereferenced and its value is the value of the second element. In this expression ++*ptr at first the value of the first element of the array is returned (that is 3) and then this value is incremented and you will get 4.

这篇关于C-具有前后增量的指针行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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