here is a sample code where myptr is passed to myfuction. It is said that it will not work. to make it working we shud pass &myptr. I have confusion here that pointer contains the address of the variable.(here an int). so when i pass this i am passing the address to the called function. so why cant i modify in the called function. what will be the difference if i pass &myptr??????
int myvar = 100;
ptr = &myvar;
//Use pointer myptr.
You can not change a variable passed into a function (in this case ptr), since it is a local copy of the value passed in. To modify anything outside of the function, you would need the address of what you want to modify (which means that it needs to be passed in as a pointer). So to modify your current pointer, you need to pass a pointer to pointer (so take the address of myPtr.
That is not the end of your problems, however, since myVar is a local variable in myfunction - the memory used by myVar is freed when the code returns. So you are now pointing at memory that is not in use.
1st, to change anything you need to pass by reference/pointer. This applies to pointers themselves as well. If you want to change the value of a pointer - where it points to (as opposed to what it points to) - then you need to pass the address of the pointer such that the called function can change it's value. So, your function would need to accept a pointer-to-pointer-to-int instead of a pointer-to-int, and you'd need to pass the address of that pointer to the called function.
2nd, you are trying to point to a local variable which will get popped off the stack the second the function ends. Even if you fix problem #1, your "returned" pointer is still going to be pointing to an area on the stack that it should probably avoid.
Good Explanation Thanks to all :)