Why am I getting segmentation fault for the pointer here?

Advertisements

Why am I getting segmentation fault here?

#include <stdio.h>
int main() {
  printf("enter the first number: ");
  int a;
  scanf("%d\n",a);
  int *pa = &a;
  printf("enter the second number: ");
  int b;
  scanf("%d\n",b);
  int *pb = &b;
  int *sum = *pa + *pb;
  printf("the sum of the given numbers is %d\n", sum);
  return 0;
}

Tried rearranging the variables but still getting the same error

>Solution :

Given both int a and int b, the respective calls to scanf should use the addresses of each variable, e.g., scanf("%d", &a);.

Alternatively, use the pointers you have created, e.g., scanf("%d", pb);.

See also: What is the effect of trailing white space in a scanf() format string?


In

int *sum = *pa + *pb;

*pa + *pb is the addition of two integer values, yielding an int, which is then converted to a pointer value of type int * and assigned to sum.

In

printf("the sum of the given numbers is %d\n", sum);

the variadic argument associated with %d must be an int (or otherise be subject to an integer promotion that yields an int), but you pass an int * instead. This invokes undefined behaviour.

To fix both issues, int *sum should be int sum.

Leave a ReplyCancel reply