For some reason, only the first element of the array is doubled. How to fix?

int increase(int*mas, int n) { for (int i = 0; i < n; i++) { return mas[i] * 2; } } 

    1 answer 1

    The fact is that you did not save the changes back to the array, and after multiplying for the first time, the result was immediately returned - this is not correct.

     void increase(int*mas, int n) { for (int i = 0; i < n; i++) { mas[i] = mas[i] * 2; } } 

    If you need to return a pointer to an array or some other result, then you need to shift it to the end of your function:

     int* increase(int*mas, int n) { for (int i = 0; i < n; i++) { mas[i] = mas[i] * 2; } // как видите, сместили возврат // за пределы Вашего цикла return mas; } 

    In this form, it will work correctly, but it does not make sense to return a pointer to mas , because when you multiply the elements and save the result in it, outside the function, the memory pointed to by mas also changes.

    • Why do I need a pointer after the function result type? - choko
    • @choko, since our mas is a pointer, then in order to return it from a function, we need the return value of the function to be a pointer too. But this is bad code, so it’s better not to do it; I wrote this section for example. - Umed