Search code examples
arrayscfor-loopcopyfunction-definition

my copy array function didn't work. i didn't understand why


This code has to copy one array to another via void copy function. But I don't understand why it doesn't work.

#include <stdio.h>

void copy(int func_array_1[], int func_array_2[], int size) {
    for (int i = 0; i < size; i++)
        func_array_1[i] = func_array_2[i];
}

int main() {

    int size = 0;
    int array[10] = { 0 };
    int copy_array[10] = { 0 };
    printf("Input the number of elements to be stored in the array :");
    scanf("%d", &size);

    for (int i = 0; i < size; i++)
        scanf("%d", &array[i]);

    copy(array, copy_array, size);

    for (int i = 0; i < size; i++)
        printf("%d", copy_array[i]);

    return 0;
}

It gives first defined array members which are all zero.


Solution

  • for (int i = 0; i < size; i++)
        func_array_1[i] = func_array_2[i];      
    

    You're copying from the zero-initialized array to the one you actually want to copy to. So just change the loop body to:

    func_array_2[i] = func_array_1[i];
    

    Using const and / or more purposeful naming could've prevented your error.