3. Write a function called copy_array. It is passed 3 parameters. The first 2 pa
ID: 3814430 • Letter: 3
Question
3. Write a function called copy_array. It is passed 3 parameters. The first 2 parameters are arrays of integers, and the 3rd parameter is the length of the array. We will assume that the lengths of the 2 arrays are the same. Here is the function's prototype:
void copy_array(int *arr1, int *arr2, int len);
Note that since an array variable is a pointer to the first element in the array, the parameters can be declared as pointers rather than using [ ].
The function should copy the integers in arr1 to arr2. For example:
int main() {
int x[ ] = {3, 1, 2};
int y[3];
int i;
copy_array(x,y,3);
for (i=0; i<3; i++)
printf("%d ", y[i]);
printf(" "); }
The output should be 3 1 2.
// 3. complete the copy_array function. Please see
// the homework write-up for details about this function.
void copy_array(int *arr1, int *arr2, int len) {
// Write your code below.
}
Explanation / Answer
#include <stdio.h>
void copy_array(int *arr1, int *arr2, int len);
int main() {
int x[ ] = {3, 1, 2};
int y[3];
int i;
copy_array(x,y,3);
for (i=0; i<3; i++)
printf("%d ", y[i]);
printf(" "); }
// 3. complete the copy_array function. Please see
// the homework write-up for details about this function.
void copy_array(int *arr1, int *arr2, int len) {
// Write your code below.
int i;
for(i=0; i<len; i++){
arr2[i] = arr1[i];
}
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
3 1 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.