Changing address contained by pointer using function
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?
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.
In C, variables are passed by value - a copy of the pointer is passed to the function. Use another pointer to the pointer instead:
void change(int **p, int *someOtherAddress)
{
*p = someOtherAddress;
}
int a = 1, b = 2;
int *p = &a;
printf("*p = %d\n", *p);
change(&p, &b);
printf("*p = %d\n", *p);
This prints
*p = 1
*p = 2
If you want to alter the content of a variable in a function in C, pointer is a kinda variable as well, you have to pass it by pointer or indirect reference by using always &
address and *
dereference operators. I mean *
operator is always used and preceded when changing the value of a variable.
#include <stdio.h>
#include <stdlib.h>
void changeIntVal(int *x) {
*x = 5;
}
void changePointerAddr(int **q) {
int *newad;
*q = newad;
}
void changePPAddr(int ***q) {
int **dummy;
*q = dummy;
}
int main() {
int *p;
int **pp;
int *tempForPP;
int a = 0;
printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
p = &a;
pp = &tempForPP;
printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
changeIntVal(&a); // ----
// |---
changePointerAddr(&p); // ---- |----> parts of what I mean
// |---
changePPAddr(&pp); // ----
printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
return 0;
}