Search code examples
cpointersvariablesinputscanf

using scanf in pointers to integer


This program tests Whether a pointer could be used as a variable to store input data.

#include <stdio.h>

int main(void)
{
    int *prt;
    printf("Input prt:");
    scanf("%d", prt);
    printf("What you inputed is: %d\n", *prt);
    return 0;
}

And the teminal log:

Segmentation fault (core dumped)

Then I wrote another test:

#include <stdio.h>

int main(void)
{
    int *p;
    int x;
    printf("Input x:");
    scanf("%d", &x);
    p = &x;
    printf("What you inputed is: %d\n", x);
    printf("What you inputed is: %d\n", *p);
    printf("The address of x: %p\n", &x);
    printf("The address p points to: %p\n", p);

    return 0;   
}

And the teminal log:

Input x:10
What you inputed is: 10
What you inputed is: 10
The address of x: 0x7ffc5f2636f4
The address p points to: 0x7ffc5f2636f4

It works well. So I got confused why I can not use prt of the first program to accept input?


Solution

  • Your variable prt is a pointer to an int, but it isn't actually initialized with a valid memory address to point to, so trying to read into it with scanf invokes undefined behavior. One likely outcome is a segmentation fault, but a segmentation fault cannot be assumed to result.

    Your second example works because &x does point to x, and so we can read into it.