0

I tried to reverse an array using only pointers. The program runs without any errors but it doesn't reverse the array. What's wrong with my code?

#include <stdio.h>

#define SIZE 10
void arrayReverseOutput(int * arr);
void arrayInput(int * arr);
void printArray(int * arr);

int main(void)
{
    int arr[SIZE] = { 0 };
    arrayInput(arr);
    arrayReverseOutput(arr);
    printArray(arr);

    system("PAUSE");
    return 0;
}

void arrayInput(int * arr){
    int i = 0;
    for (i = 0; i < SIZE; i++){
        scanf("%d",(arr+i));
    }
}

void arrayReverseOutput(int * arr){
    int i = 0;
    int k = SIZE-1;
    int temp = 0;


    for (i = 0; i < SIZE; i++){
        temp = *(arr+i);
        *(arr+i) = *(arr + k);
        *(arr + k) = temp;
        k--;
    }
}

void printArray(int * arr){
    int i = 0;
    for (i = 0; i < SIZE; i++){
        printf("%d ", *(arr+i));
    }
}
1
  • What do you mean by "using only pointers"? Commented Apr 6, 2017 at 8:03

2 Answers 2

3

The problem is, you are actually reversing the array twice, negating any changes achieved by swapping places.

Loop over only half of the array while swapping the elements, like

 for (i = 0; i < SIZE/2; i++)
Sign up to request clarification or add additional context in comments.

1 Comment

'you are actually reversing the array twice' - you knew that before opening the question, yes? :)
2

You can use 2 pointers to do so

void arrayReverseOutput(int *head, int *tail)
{
    int temp = 0;

    do
    {
        temp = *tail;
        *tail = *head;
        *head = temp;
    }
    while (head++ < tail--);
}

Complete code

#include <stdio.h>

#define SIZE 10
void arrayReverseOutput(int *head, int *tail);
void arrayInput(int * arr);
void printArray(int * arr);

int main(void)
{
    int arr[SIZE] = { 0 };
    arrayInput(arr);
    arrayReverseOutput(arr, &arr[SIZE - 1]);
    printArray(arr);

    return 0;
}

void arrayInput(int * arr)
{
    int i = 0;
    for (i = 0; i < SIZE; i++)
    {
        scanf("%d", (arr + i));
    }
}

void arrayReverseOutput(int *head, int *tail)
{
    int temp = 0;

    do
    {
        temp = *tail;
        *tail = *head;
        *head = temp;
    }
    while (head++ < tail--);
}

void printArray(int * arr)
{
    int i = 0;
    for (i = 0; i < SIZE; i++)
    {
        printf("%d ", *(arr + i));
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.