C程序:分段故障 [英] C program :segmentation fault
问题描述
林新的C编程和即时通讯在我的code得到一个分段错误的地方。该方案采用返回功能要求用户对他们多少钱,在他们的银行账户开始。以后我会添加code计算interest.Thanks在此找我作为有许多麻烦IM找出为什么即时得到这个错误。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT getPV()
{
INT D组;
INT开始;
的printf(开始:);
scanf函数(%D开头);
D =启动;
返回D组;
}
诠释的main()
{
INT PV;
PV = getPV();
打印(%D,PV);
返回0;
}
当你调用scanf函数,你需要通过地址要存储这些变量
的值。
这意味着,如果你想存储在变量中的值启动
,你需要通过起始地址
到 scanf函数
。
您可以得到一个变量的使用&安培的地址;
运营商。所以,你需要改变你scanf函数为:
scanf函数(%d个,&安培;启动);
您使用 scanf函数(%D,开始)时,你得到的分割故障;
,因为启动
是一个自动变量,并会在它有一个垃圾(随机)值分配一定的参考价值之前。 scanf函数
将把这个随机值作为地址,该用户输入的值已经被存储到。现在,当 scanf函数
尝试将用户输入的值存储到该随机地址的位置,你会得到段错误,因为在你的程序不能访问该地址位置最可能性。
Im new to C programing and im getting a segmentation fault somewhere in my code. The program uses a return function to ask a user for the start of how much money they have in their bank account. later I will add code to calculate the interest.Thanks for looking at this for me as im having lots of trouble finding out why im getting this error.
#include <stdio.h>
#include <stdlib.h>
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;
}
When you call scanf, you need to pass the address of the variable
to which you want to store the value.
That means, if you want to store the value in variable start
, you need to pass the address of start
to scanf
.
You can get the address of a variable using the &
operator. So you need to change you scanf to:
scanf("%d", &start);
You get segmentation fault when using scanf("%d", start);
because, start
is an automatic variable and will have a garbage (random) value in it before you assign some value to it. scanf
will treat this random value as the address to which the user entered value has to be stored. Now when scanf
tries to store user entered value to this random address location, you get segmentation fault, because in most likelihood your program is not allowed to access that address location.
这篇关于C程序:分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!