Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ",p);
    change_adrs(p);
    printf("
 the address is %u ",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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...