1

I want to make a reversed array for another array in C.

For example:

int nums[6]={1,2,3,4,5,6};

I want "reversed" to be the reversed array of array noms

int reverse[6]={6,5,4,3,2,1};

What I have so far:

#include <stdio.h>
#include <string.h>

int main(){
int nums[6]={1,2,3,4,5,6};
int size=sizeof(nums)/sizeof(nums[0]);
int reversed[size];


for (int i=size;i>0;i--){
reversed[size-i]=nums[i];

}
return 0;
}
3
  • You have not actually asked a question or described a specific problem. If the code is not working as you expect run it in a debugger and step through it line by line. Commented Dec 14, 2020 at 3:54
  • For starters, what are the indices of the arrays in the first iteration of the loop? Does it look correct to you? Commented Dec 14, 2020 at 3:55
  • 1
    Your accessing nums out fo range. On the first iteration i is size and you fetch nums[i], therefore nums[size]. Allowable indexes are 0..(size-1). Therefore, your program invokes undefined behavior. Commented Dec 14, 2020 at 4:07

1 Answer 1

4

A very simple function to reverse an array would be:

void reverse(int array[], int start, int end)
{
  int tmp;
  while (start < end)
  {
    tmp = array[start]; 
    array[start] = array[end];
    array[end] = tmp;
    start++;
    end--;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

More accurately, the function reverses a segment of an array. It reverses an array when the start is zero and the end is the index of the last element of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.