Welcome to Jonic Developer Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - 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 ",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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Jonic Developer Community for programmer and developer-Open, Learning and Share

Just Browsing Browsing

[6] html - How to create even cell spacing within a

548k questions

547k answers

4 comments

40.3k users

...