C程序:分段错误

我是C编程的新手,我在代码中的某个地方遇到了分段错误。 该程序使用返回function向用户询问他们在银行帐户中有多少钱。 稍后我会添加代码来计算兴趣。谢谢你为我看这个,因为我很难找到为什么我得到这个错误。

#include  #include  int getPV() { int d; int start; printf("Start: "); scanf("%d", start); d = start; return d; } int main() { int pv; pv = getPV(); print("%d",pv); return 0; } 

调用scanf时,需要传递要存储值address of the variableaddress of the variable

这意味着,如果要将值存储在变量start ,则需要将address of startaddress of start传递给scanf

您可以使用&运算符获取变量的地址。 所以你需要将scanf更改为:

 scanf("%d", &start); 

使用scanf("%d", start);时会出现分段错误scanf("%d", start); 因为, start是一个自动变量,在为其赋值之前会有一个垃圾(随机)值。 scanf会将此随机值视为必须存储用户输入值的地址。 现在,当scanf尝试将用户输入的值存储到此随机地址位置时,会出现分段错误,因为很可能您的程序不允许访问该地址位置。