How to change value of variable passed as argument?

后端 未结 4 1833
天涯浪人
天涯浪人 2020-11-22 09:03

How to change value of variable passed as argument in C? I tried this:

void foo(char *foo, int baa){
    if(baa) {
        foo = \"ab\";
    } else {
                


        
4条回答
  •  迷失自我
    2020-11-22 09:26

    You're wanting to change where a char* points, therefore you're going to need to accept an argument in foo() with one more level of indirection; a char** (pointer to a char pointer).

    Therefore foo() would be rewritten as:

    void foo(char **foo /* changed */, int baa)
    {
       if(baa) 
       {
          *foo = "ab"; /* changed */
       }
       else 
       {
          *foo = "cb"; /* changed */
       }
    }
    

    Now when calling foo(), you'll pass a pointer to x using the address-of operator (&):

    foo(&x, 1);
    

    The reason why your incorrect snippet prints baa is because you're simply assigning a new value to the local variable char *foo, which is unrelated to x. Therefore the value of x is never modified.

提交回复
热议问题