Emmanuel Goldstein
Emmanuel Goldstein

Reputation: 112

Why am I getting a segmentation fault error with the following code?

I'm a Python programmer studying C. I receive a segmentation fault on the final printf() of the following code. I'm sure it has something to do with the expression but I'm not sure what the problem is. Unfortunately, the expression works in Python so I'm unable to get a more specific error message. I'm using the GCC compiler in Debian.

#include <stdio.h>

int main(void)
{

  int n;

  printf("Enter a two-digit number: ");
  scanf("%d",n);

  printf("The reversal is: %d\n", (n % 10) * 10 + (n / 10));
  return 0;
}

Upvotes: -1

Views: 66

Answers (3)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

You need to provide a pointer to an int as the argument to scanf, not the int itself; &n rather than just n.

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44316

try scanf("%d",&n);

it has no way to put anything into n unless it has a pointer to n

Upvotes: 0

Rohan
Rohan

Reputation: 53386

Pass address of n to scanf() as

scanf("%d", &n);

Upvotes: 2

Related Questions