Changing array inside function in C

前端 未结 7 1988
伪装坚强ぢ
伪装坚强ぢ 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:23

    To use pass by value:
    Make the following change:
    In function change(...), replace:

    int i;for(i=0;i

    To:

    int i;for(i=0;i

    EDIT:
    But to use pass by reference:

    //To change the contents of a variable via a function call
    //the address of that variable has to be passed. So, if you
    //want to change the contents of an array of int, i.e. int *array, you 
    //need to pass its address, not the variable itself,  using the 
    //address of operator, it would look like this &array (read _the address of
    // pointer to int "array")
    //This requires you to change the prototype of your function:
    void change2(int **a, int len)
    {
        int i;
        for(i=0;i

    Then in main, make the following changes, and it will work as you purposed:

    int main(){
        int i,length=10;
        int *array;
    
        array = calloc(length, sizeof(int));
        if(!array) return 0;
        //or malloc if preferred.  But note, in C, 
        //casting the output is not required on either.
        //array = malloc(length*sizeof(int));
        //if(!array) return 0;
    
        for(i=0;i

提交回复
热议问题