0

How to write a C Function to swap elements of 2 arrays according to the smallest array in size

I need it to be in one function, just call it in main like this code, but this doesn't work: #include <stdio.h> #include <stdlib.h> void swap(int *arr1, int arr1_size, int *arr2, int arr2_size) { int temp; temp = *arr1; *arr1 = *arr2; *arr2 = temp; int i; int size = (arr1_size < arr2_size? arr1_size : arr2_size); for(i=0;i<size;i++) { printf("arr1=%d \n arr2=%d \n",arr1[i],arr2[i]); } } int main() { int a[5]={1,2,3,4,5}; int b[3]={10,20,30}; swap(&a[5], 5, &b[3], 3); return 0; } ------------------------------------------------------------- I tried this outside main and its okay, but this is not what I want: #include <stdio.h> #include <stdlib.h> void swap(int *arr1, int *arr2) { int temp; temp = *arr1; *arr1 = *arr2; *arr2 = temp; } int main() { int i; int a[5]={1,2,3,4,5}; int a_size=5; int b[3]={10,20,30}; int b_size=3; int size = (a_size < b_size? a_size : b_size); for(i=0;i<size;i++) { swap(&a[i], &b[i]); printf("a=%d \n b=%d \n",a[i],b[i]); } return 0; } the answer is: a=10 b=1 a=20 b=2 a=30 b=3 and the other 2 elements have been removed, is it correct?

14th Oct 2018, 12:24 PM
Aisha Ali
Aisha Ali - avatar
1 Antwort
+ 2
#include <stdio.h> #include <stdlib.h> void swap(int*a,int*b,int a_size,int b_size){ int size = (a_size < b_size? a_size : b_size); int i; for(i=0;i<size;i++) { int temp = a[i]; a[i] = b[i]; b[i] = temp; printf("a=%d \n b=%d \n",a[i],b[i]); } } int main() { int i; int a[5]={1,2,3,4,5}; int a_size=5; int b[3]={10,20,30}; int b_size=3; swap(a,b,a_size,b_size); return 0; }
14th Oct 2018, 4:01 PM
Tanay
Tanay - avatar