0

I want to Print Pointer Array value in Reverse

#include <stdio.h>
#define size 5
int main()
{
  int a[size] = {1,2,3,4,5};
  int i;
  int *pa = a;
  for(i = size; i >0; i--)
  {
    printf("a[%d] = %d\n",i,*pa);
    pa++;
  }
  return 0;
}

Output:

a[5] = 1    
a[4] = 2
a[3] = 3    
a[2] = 4    
a[1] = 5

The output I want is:

a[5] = 5    
a[4] = 4    
a[3] = 3    
a[2] = 2    
a[1] = 1
1
  • 2
    Out of curiosity, are you surprised by the current result? Commented Feb 28, 2019 at 19:07

3 Answers 3

3

replace with this

#include <stdio.h>
#define size 5
int main()
{
  int a[size] = {1,2,3,4,5};
  int i;
  int *pa = (a+size-1);
  for(i = size; i >0; i--)
  {
    printf("a[%d] = %d\n",i,*pa);
    pa--;
  }
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You're making this too hard. Given a pointer into an array, you can use the indexing operator on it just as you would on the array itself:

    int a[size] = {1,2,3,4,5};
    int i;
    int *pa = a;
    for (i = size - 1; i >= 0; i--) {
        printf("a[%d] = %d\n", i, pa[i]);
    }

Alternatively, if you want to avoid the indexing operator for some reason, then just start your pointer at one past the end ...

    *pa = a + size;

... and decrement it as you proceed through the loop:

    for (i = size - 1; i >= 0; i--) {
        pa--;
        printf("a[%d] = %d\n", i, *pa);
    }

Do note, by the way, that array indexing in C starts at 0, as the example codes above properly account for.

Comments

0

You don't have to use pointer. A simpler implementation

#include <stdio.h>
#define size 5
int main()
{
  int a[size] = {1,2,3,4,5};
  for(int i = size-1; i >=0; i--)
    printf("a[%d] = %d\n",i,a[i]);
  return 0;
}

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.