Updating pointers in a function

前端 未结 5 1433
鱼传尺愫
鱼传尺愫 2020-12-11 03:52

I am passing a pointer a function that updates it. However when the function returns the pointer it returns to the value it had prior to the function call.

Here is m

相关标签:
5条回答
  • 2020-12-11 04:39

    C uses pass-by-value for function parameter passing. The value of pSrc is just a copy of the pSrc present in main(), not the same entity as the pSrc from main(). That is why, any changes made to pSrc inside the function func()won't be reflected in main() (caller function).

    However, all the changes to *pSrc will sustain.

    Solution: To change the pSrc of main() from func(), you need to pass a pointer to pSrc (pointer to a pointer) from main() and adjust the data types accordingly. Also, in that case, please note, the pSrc should be modifiable (present in read-write memory). As it is currently written, the pSrc in main() is not modifiable.

    0 讨论(0)
  • 2020-12-11 04:43

    The pointer inside the function is a copy of the passed pointer.

    They both hold the same address but have different addresses, so changing the address held by one of them doesn't affect the other.

    If you want to increment the pointer inside the function pass it's address instead, like this

    static void func(char **pSrc) {
        int x;
        for ( x = 0; x < 10; x++ ) {
            (*pSrc)++;
        }    
        printf("Pointer Within Function: %p\n", pSrc  );
    }
    

    and

    func(&pSrc);
    

    Also, be careful not to modify the contents, because your pointer points to a string literal, and string literals cannot be modified.

    0 讨论(0)
  • 2020-12-11 04:44

    C is passing parameters by value, so it makes a copy of pSrc inside your function, and all the changes you've made are applied to a copy of pSrc. If you want to change the value of pSrc, then you should pass a pointer to pSrc, like this:

    static void func(char **pSrc){ // pointer to char*
         int x;
         for (x = 0; x < 10; x++)
             (*pSrc)++
    }
    
    0 讨论(0)
  • 2020-12-11 04:44

    You call func by passing pSrc. You think you are passing the same variable - That is func will operate on the same memory location when it alters pSrc. This is false.

    func gets a copy of pSrc. The stack frame built in calling func will have its own pSrc. What is modified is its version not the calling function's.

    To let func operate on the actual variable in main you got to pass address of pSrc - &pSrc.

    Relevant concepts - Pass by Value and Pass by Reference.

    0 讨论(0)
  • 2020-12-11 04:50

    When you give a pointer to a function, you have a copy of the reference value that you originally had.

    Then, if you modify your pointer, you're modifying a copy.

    If you want to update the original one, you need to pass it with a double pointer ** which will let you modify the original pointer, passing a "reference to a reference" (double pointer).

    0 讨论(0)
提交回复
热议问题