在指向整数的指针中使用 scanf

问题描述 投票:0回答:1

此程序测试指针是否可以用作变量来存储输入数据。

#include<stdio.h>

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

和终端日志:

Segmentation fault (core dumped)

然后我写了另一个测试:

#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;   
}

和终端日志:

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

效果很好。所以我很困惑为什么我不能使用

prt
接受输入?

c pointers variables input scanf
1个回答
0
投票

您的变量

prt
是一个指向int的指针,但它实际上并未初始化,因此尝试读取它会调用未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.