Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
pranphy Avatar asked Nov 17 '12 13:11

pranphy


People also ask

Can a pointer variable be changed within a function?

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.

Can you reassign a pointer in C?

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.

How do you increment the address of a pointer?

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.


1 Answers

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.

like image 142
mathematician1975 Avatar answered Sep 20 '22 10:09

mathematician1975