Incrementing Pointers

吃可爱长大的小学妹 提交于 2019-12-04 06:31:01
*pPointer++;

is equivalent to

*pPointer;
pPointer++; 

so it increments the pointer, not the dereferenced value.

You may see this from time to time in string copy implementations like

  while(*source)
    *target++ = *source++;

Since your problem is a matter of operator precedence, if you want to deref the pointer, and then increment, you can use parens:

(*pointer)++;

++ operator precedence is higher than *d dereference.

What you write is actually

*(p++)

However you should use

(*p)++

In the Second program you are not increasing the the content at the pPointer address, but you are increasing the pointer. So suppose here if the pPointer value(memmory location allocated to iTuna) is 1000 then it will increase the location to 1000+2(int size)=1002 not the content to 1+1=2. And In the above program you are accessing the pointer location contents. Thats why you are not getting the expected results

 *ptr++; - increment pointer and dereference old pointer value

It's equivalent to:

*(ptr_p++) - increment pointer and dereference old pointer value

Here is how increment the value

(*ptr)++; - increment value

That's becuase ++ has greater precedence than *, but you can control the precedence using ()

*pPointer++; - Here dereference operator(*) has more precedence than increment operator(++). So this statement is first dereferencing and incrementing the pointer. After this you are printing the value of iTuna which will give you the same value. You are not printing the value by dereferencing pointer variable(*pPointer), because this will leads to crash(undefined behaviour). Because pPointer is now incremented.

Use like (*pPointer)++; to increment the value which is pointed by pPointer.

To get clear idea print the address stored in pPointer variable before and after your increment statement.

In the first case, the content of the pointer is incremented because *pPointer correspond to the content of the variable iTuna.

In the second one, the content is not incremented because you pPointer incrementing the pointer address. Remembering operator precedence rules, postfix operators such as increment (++) and decrement (--), have higher precedence than prefix operators, such as the dereference operator (*). Therefore, writting

*pPointer++

is equivalent to

*(pPointer++)

And what it does is to increase the value of pPoiner (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).

The correct code to have what you are expecting for is the following:

++*pPointer

or

(*pPointer)++

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!