Answer the question
In order to leave comments, you need to log in
How to reverse an array by 2 elements?
I can’t think of implementing the reverse of an array of the form:
arr1 = 1, 2, 3, 4, 5, 6, 7, 8
Reverse
arr2 = 7, 8, 5, 6, 3, 4, 1, 2
That is, the reverse goes two element in the opposite direction. I keep leaking memory
#include <stdio.h>
int main (){
int arr1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
inr arr2[8], i = 0, j = 8;
for (i = 0; i < 8; i++, j--){
arr2[i] = arr1[j - 1];
arr2[i + 1] = arr1[j];
printf("%d ", arr2[i]);
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
[[email protected] ~]$ cat foobar.c
#include <stdio.h>
int main () {
int arr1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arr2[sizeof(arr1) / sizeof(arr1[0])];
for (size_t i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i += 2)
printf("%d %d ", arr1[i], arr1[i + 1]);
printf("\n");
for (size_t i = 0, j = sizeof(arr1) / sizeof(arr1[0]) - 1; i < sizeof(arr1) / sizeof(arr1[0]); i += 2, j -= 2) {
arr2[i] = arr1[j - 1];
arr2[i + 1] = arr1[j];
}
for (size_t i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i += 2)
printf("%d %d ", arr2[i], arr2[i + 1]);
printf("\n");
return 0;
}
[[email protected] ~]$ gcc foobar.c -o foobar
[[email protected] ~]$ ./foobar
1 2 3 4 5 6 7 8
7 8 5 6 3 4 1 2
[[email protected] ~]$
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question