Changing address contained by pointer using function

后端 未结 5 593
终归单人心
终归单人心 2020-11-21 06:49

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; w

5条回答
  •  灰色年华
    2020-11-21 07:06

    For a primitive data type such as an int, the double pointers are not necessary. You can write directly into the address where the int is stored, treating its address as a pointer in the function being called. This is unlike a char array ("string") where the size of what is pointed to is variable and you must therefore use another level of indirection when changing it from within a called function. Try this:

    void foo(int *oldVal)
    {
        int newVal = 99;    // or whatever you want
        *oldVal = newVal;
    }
    
    int main(int argc, char *argv[])
    {
        int someVal = 0;
        foo(&someVal);      // we send its address to foo()
    
        printf("someVal is now %d.\n", someVal);
    
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题