Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting segmentation fault for the pointer here?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading