Incremental pointers

I have a question about increasing pointers, which I don't quite understand.

Allows you to see two small programs:

int iTuna=1; int* pPointer= &iTuna; *pPointer = *pPointer + 1 ; //Increment what pPointer is pointing to. cout << iTuna << endl; 

In this first program, I increment what pPointer points to this "* pPointer = * pPointer +1". And since I expected iTuna to change to "2" and the program will print the value "2"

 int iTuna=1; int* pPointer= &iTuna; *pPointer++; //Increment what pPointer is pointing to. cout << iTuna << endl; system("PAUSE"); return 0; 

Here I incremented the increment pointed to by pPointer, this is "* pPointer ++". But here iTuna remains “1” and the programs print out the value “1”. Although I expected this to work first, it is not.

Please help me and tell me why the second piece of code does not work, as I expected, and how to get around it.

thanks

+6
source share
5 answers
 *pPointer++; 

equivalently

 *pPointer; pPointer++; 

so that it increments the pointer, not the dereferenced value.

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

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

Since your problem is with operator precedence, if you want to split the pointer and then increment, you can use parens:

 (*pointer)++; 
+9
source

++ operator precedence is higher than * d dereferencing.

Actually you write

 *(p++) 

However you should use

 (*p)++ 
+2
source
  *ptr++; - increment pointer and dereference old pointer value 

This is equivalent to:

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

Here's how the value increases

 (*ptr)++; - increment value 

That ++ has a higher priority than * , but you can control the priority using ()

+1
source

In the second program, you do not increase the content at the pPointer address, but you increase the pointer. Suppose that if the pPointer value (memmory place allocated by iTuna) is 1000, then it will increase the location to 1000 + 2 (int size) = 1002, and not to 1 + 1 = 2. And in the above program, you get access to the content pointer location. That is why you do not get the expected results.

+1
source

*pPointer++; - Here, the dereference operator ( * ) has more priority than the increment operator ( ++ ). Thus, this statement is the first dereference and increase of the pointer. After that, you print the iTuna value, which will give you the same value. You are not printing the value with a pointer dereferencing pointer ( *pPointer ), because this will lead to failure (undefined behavior). Since pPointer now increasing.

Use, for example, (*pPointer)++; to increase the value pointed to by pPointer .

To get a clear idea, type the address stored in the pPointer variable before and after your increment operator.

0
source

Source: https://habr.com/ru/post/921825/


All Articles