If I've declared a pointer p
as int *p
; in main module, I can change the address contained by p
by assigning p = &a;
where a
is another integer variable already declared. I now want to change the address by using a function as:
void change_adrs(int*q) { int *newad; q = newad; }
If I call this function from main module
int main() { int *p; int a = 0; p = &a; // this changes the address contained by pointer p printf("The address is %u\n", p); change_adrs(p); printf("The address is %u\n", p); // but this doesn't change the address return 0; }
the address content is unchanged. What's wrong with using a function for same task?
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
Although it might appear that they represent similar concepts, one of the important differences is that you can reassign a pointer to point to a different address, but you cannot do this with a reference.
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
In C, functions arguments are passed by value. Thus a copy is made of your argument and the change is made to that copy, not the actual pointer object that you are expecting to see modified. You will need to change your function to accept a pointer-to-pointer argument and make the change to the dereferenced argument if you want to do this. For example
void foo(int** p) { *p = NULL; /* set pointer to null */ } void foo2(int* p) { p = NULL; /* makes copy of p and copy is set to null*/ } int main() { int* k; foo2(k); /* k unchanged */ foo(&k); /* NOW k == NULL */ }
If you have the luxury of using C++ an alternative way would be to change the function to accept a reference to a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With