Changing array inside function in C

前端 未结 7 1983
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 08:40

I am learning C and confused why a array created in the main wont change inside the function, i am assuming the array passed is a pointer, and changing the pointer should\'v

7条回答
  •  清歌不尽
    2020-12-01 09:07

    Your array in main is an array. It will decay to a pointer, to produce the behavior you expect, but it is not a pointer.

    int a[10];
    int* p = a; // equivalent to &a[0]; create a pointer to the first element
    a = p;      // illegal, a is NOT a pointer.
    

    What your code is doing is copying the address of a into a function-local variable. Modifying it will have no more difference outside than changing length.

    void change(int* local_ptr, size_t length)
    {
        local_ptr = 0;
        length = 0;
    }
    
    int main()
    {
        int a[10];
        int length = 10;
        printf("before a=%p, length=%d\n", a, length);
        change(a, length);  // we copied 'a' into 'local_ptr'. 
        printf("after a=%p, length=%d\n", a, length);
    }
    

    If you wish to modify a pointer from the caller, you will need to use pointer-to-pointer syntax:

    void change(int** ptr, size_t length)
    {
        // change the first element:
        **ptr = 0;
        // change the pointer:
        *ptr = 0;
        // but ptr itself is a function-local variable
        ptr = 0;  // local effect
    }
    

    However: There is a problem with what you are trying to do that goes deeper than this.

    In your code, "int a" is an array on the stack, not an allocated pointer; you cannot free it and you should avoid mixing heap/stack pointers this way because eventually you'll free the wrong thing.

提交回复
热议问题