Changing array inside function in C

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

    You pass a pointer to the array array to the function change. In this function you create another array called new (using new as a name is a bad idea) and then assign it to the locally created function parameter array. You do not modify pointer in your main function. If you would like to do so, you should use

    array = change(array,length);
    

    in your main function and

    int *change(int *array, int length) {
        int *variable_called_new =(int *)malloc(length*sizeof(int));
        [...]
        return variable_called_new
    }
    

    in your change function.

提交回复
热议问题