4th Nov 2021, 5:22 AM
Saumya Mishra
Saumya Mishra - avatar
5 Réponses
+ 2
The function receives a pointer, which is the right way to allow the function to change the value the pointer points to. But x -= 2 changes the pointer, not the value. For you to change the value, you have to reference memory location the pointer points to. That is - deference the pointer. In short, use '*' before the variable.
4th Nov 2021, 10:53 PM
Emerson Prado
Emerson Prado - avatar
+ 6
Inside fun(), x is a copy of the pointer . So if we change x to point something else then remains uneffected. If we want to change a local pointer of one function inside another function, then we must pass pointer to the pointer. By passing the pointer to the pointer, we can change pointer to point to something else. 
4th Nov 2021, 5:51 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 6
Rishi ohh you are right sorry i haven't noticed x properly i misunderstood what actually i was trying to say for example. void fun(int **pptr) { static int q = 10; *pptr = &q; } int main() { int r = 20; int *p = &r; fun(&p); printf("%d", *p); } i found this question on geeksforgeeks  the function fun() expects a double pointer (pointer to a pointer to an integer). Fun() modifies the value at address pptr.  The value at address pptr is pointer p as we pass adderess of p to fun().  In fun(), value at pptr is changed to address of q.  Therefore, pointer p of main() is changed to point to a new variable q. Also, note that the program won’t cause any out of scope problem because q is a static variable. Static variables exist in memory even after functions return. For an auto variable, we might have seen some unexpected output because auto variable may not exist in memory after functions return.
4th Nov 2021, 6:19 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
You changed the pointer's memory location to 2 units backwards. To achieve what you're probably trying, you need to use the dereference operator '*'. Here is your code fixed https://code.sololearn.com/c97xRm6XnJP0/?ref=app
4th Nov 2021, 6:05 AM
Rishi
Rishi - avatar
+ 3
♨️♨️ I think you probably misunderstood the question. Refer my answer, you'll get it =)
4th Nov 2021, 6:05 AM
Rishi
Rishi - avatar