此程序测试指针是否可以用作变量来存储输入数据。
#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
接受输入?
您的变量
prt
是一个指向int的指针,但它实际上并未初始化,因此尝试读取它会调用未定义的行为。