Furqan Mohammed
Furqan Mohammed

Reputation: 11

Print Array Pointer value in Reverse Order

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

Upvotes: 0

Views: 133

Answers (3)

stensal
stensal

Reputation: 401

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;
}

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180141

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.

Upvotes: 2

nissim abehcera
nissim abehcera

Reputation: 831

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;
}

Upvotes: 2

Related Questions