Difference between pointers

int array[10]; int main (){ int *data_ptr; int value; data_ptr = &array[0]; value = *data_ptr++; value = *++data_ptr; value = ++*data_ptr; return 0; } 

What is the difference between each assignment?

If I print after each value assignment, it returns

 0 0 1 
+4
source share
3 answers
 value = *data_ptr++; 

This assigns the result of dereferencing data_ptr to value , and then increments data_ptr . Thus, the first element of the array, which is 0, will be in value , and data_ptr will point to the second. This is because ++ has a higher priority, so it applies to data_ptr , not *data_ptr .

 value = *++data_ptr; 

This first increases data_ptr (so in this case it points to the third element of the array instead of the second), and then it saves the dereference result (i.e. the third element of the array, which is also 0) to value .

 value = ++*data_ptr; 

Here, the result of dereferencing data_ptr (the third element of the array) + 1 is saved (so, only 1, since all elements of your array are automatically initialized to 0 in this case) in value .

+4
source

a

 // Increment data_ptr and return the *original* value, then dereference that. value = *data_ptr++; // Increment data_ptr and return the new value, then dereference that value = *++data_ptr; // Dereference data_ptr then increment the result and return // the newly incremented value. value = ++*data_ptr; 

To make it clear, here the same is written with a long hand

 //1 data_ptr+=1; int* prev = data_ptr - 1; value = *prev; //2 data_ptr += 1; value = *data_ptr; //3 value = *data_ptr; value+=1; 
0
source

Looks like me. The global array[] initialized to zeros. The first value = *data_ptr gets the value a [0], and then increments the pointer. The next line again increases the pointer and gets [2]. The last line gets the value [2], and then increments the value, giving 1.

0
source

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


All Articles