-1

I want to reverse an array element using pointer But why i getting out-put as 4 3 3 4 when i give input 1 2 3 4

here my code

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    int n, a[100], *ptr;
    printf("enter array size: ");   
    scanf("%d",&n);
    printf("enter array element: ");
    for(int i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }

    ptr = &a[0];
    int j=0;
    int i = n-1;

    while(j != n)
    {   
        a[j] = *(ptr+i);
        j++;
        i--;
    }

    // for printing output

    printf("\nin reverse: \n");
    for(int k=0; k<n; k++)
    {
        printf("%d, ",a[k]);
    }

    return 0;
}

can anybody tell me what is the problem here ?

Joy Kumar Bera
  • 314
  • 2
  • 8

2 Answers2

2
while(j != n)
{   
    a[j] = *(ptr+i);
    j++;
    i--;
}

This isn't actually swapping the two values. It's simple setting the first half. In order to swap them you'd add a line like:

while(j != n / 2)
{   
    int temp = a[j];
    a[j] = *(ptr+i);
    *(ptr + i) = temp;
    j++;
    i--;
}
Matthew Kerian
  • 812
  • 5
  • 18
-1

In your code you are overwriting the values..

In order to reverse numbers in place by using pointers, replace the while-loop as below in your code.

int* ptr_start = a;
int* ptr_end = a + (sizeof(a) / sizeof(a[0])) - 1;
 while (ptr_start < ptr_end) {
        *ptr_end   ^= *ptr_start;
        *ptr_start ^= *ptr_end ;
        *ptr_end   ^= *ptr_start;
        ptr_start++;
        ptr_end--;
      }

Note: There will be an -ve impact on performance.

ntshetty
  • 1,293
  • 9
  • 20
  • Instead just mark negative, have patience to put a comment, so that will help some one.. Read question and my answer.. suggest why it's not right answer – ntshetty Dec 05 '18 at 06:53
  • 1
    Your answer is needlessly complex for his solution, and is inefficient – Matthew Kerian Dec 05 '18 at 13:37
  • @MatthewKerian i don't think the question talks about efficiency and more over he want achieve with pointers. In that context is the solution is wrong ? – ntshetty Dec 06 '18 at 03:03
  • If I asked you the directions to a restaraunt down the street would you take me all over the place? For arrays you're always using pointers – Matthew Kerian Dec 06 '18 at 04:54
  • @MatthewKerian off-course yes if all the roads blocked or customer wants. Is that the crime ?? – ntshetty Dec 06 '18 at 06:13
  • Except in this case there was a wide open rode he wanted to take that you ignored. The other answer posted solves it much cleaned while also being more efficient – Matthew Kerian Dec 06 '18 at 06:24
  • that Edited with note, but if you don't know `xor operation`, it means is not cleaner ?? – ntshetty Dec 06 '18 at 06:26
  • https://stackoverflow.com/questions/36906/what-is-the-fastest-way-to-swap-values-in-c – Matthew Kerian Dec 06 '18 at 07:15
  • That's comes when efficiency matters not the methods to explore. – ntshetty Dec 06 '18 at 07:24