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,340
  • 1
  • 12
  • 25
user3870509
  • 307
  • 1
  • 3
  • 7

3 Answers3

2

You should allocate memory for pointers like this:

int* n = (int*)malloc(sizeof(int))
cppcoder
  • 22,227
  • 6
  • 56
  • 81
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
  • 3,054
  • 24
  • 32
0

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

Fizzix
  • 23,679
  • 38
  • 110
  • 176