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.
CodePudding user response:
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.
CodePudding user response:
You have a typo in the function
for (int i = 0; i < size; i )
func_array_1[i] = func_array_2[i];
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
As the function is called like
copy(array, copy_array, size);
you have to write
for (int i = 0; i < size; i )
func_array_2[i] = func_array_1[i];
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
The reason of the typo is a bad function declaration. The function should be declared at least like
void copy( const int func_array_1[], int func_array_2[], int size);
That is the array that is not being changed within the function should be declared with the qualifier const
.
Instead of the for loop you could use the standard function memcpy
declared in the header <string.h>
as for example
memcpy( func_array_2, func_array_1, size * sizeof( int ) );
Pay attention to that you need to check that the entered value of the variable size
is not greater than 10
.