0

This is my program :

#include<stdio.h>
int main()
{
    int *n;
    int var;
    scanf("%d",n);
    printf("%d",*n);

}

as scanf stores the value at specified address I am giving the address .Then I am trying to print value at address but its giving segfault.

Gutblender
  • 1,300
  • 1
  • 12
  • 24
user3870509
  • 277
  • 1
  • 2
  • 7

3 Answers3

2

You should allocate memory for pointers like this:

int* n = (int*)malloc(sizeof(int))
cppcoder
  • 20,990
  • 6
  • 49
  • 78
2

It's because a block of memory has not been allocated to contain the integer value referenced by the variable n. You have only initialized a pointer to the memory block, not the memory block itself.

If you instead do the following, the code will work:

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    printf("%d", n);
}
wookie919
  • 2,924
  • 21
  • 29
0

var n is pointer, and you didn't malloc memory for it.

Fizzix
  • 22,389
  • 37
  • 108
  • 168