0

I have to display the numbers in reverse order but i get an error program terminated to "Segmentation fault"(11).

My code:

#include<stdio.h>
void main()
{
    int a,b[100],i;
    printf("Enter the total numbers:\n");
    scanf("%d",&a);
    printf("Enter the numbers:\n");
    for(i=0;i<a;i++)
    {
        scanf("%d",&b[i]);
    }
    for(i=a-1;i>=0;i++)
    {
        printf("%d\n",b[i]);
    }
}
Joey
  • 13
  • 1
  • 4
  • What debugging and other troubleshooting have you done so far? – David Hoelzer Jul 24 '17 at 18:05
  • 2
    you should also change your `main` signature to [`int main(void)`](https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function/) and check that `a` doesn't exceed the number of elements in `b`. – yano Jul 24 '17 at 18:14

2 Answers2

3

You need to replace i++ with i--

#include<stdio.h>
void main()
{
    int a,b[100],i;
    printf("Enter the total numbers:\n");
    scanf("%d",&a);
    printf("Enter the numbers:\n");
    for(i=0;i<a;i++)
    {
        scanf("%d",&b[i]);
    }
    for(i=a-1;i>=0;i--)
    {
        printf("%d\n",b[i]);
    }
}
Jade
  • 120
  • 1
  • 2
  • 13
2

Segmentation fault occurs when you are trying to access un-referenced memory or going out of bounds. So as mentioned just change i++ to i-- in second loop.

rahul kanojia
  • 57
  • 1
  • 6
  • Adding a few lines of code always helps. This could be written as a comment instead of a separate answer. – Nitesh Jul 24 '17 at 18:47