Reputation: 9
I am new to C and I am using a scanf function. The number I am asking the user to input is a long integer named myNumber. However, when I put in the value, the program gives "segmentation fault: 11"
long double ObtainNumber (myNumber)
{
scanf("%lf", &myNumber);
while (myNumber > 999999999)
{
printf("Error. Please enter a number with no greater than 9 digits\n");
scanf("%lf", &myNumber);
}
return (myNumber);
}
I was wondering what I am doing wrong?
Upvotes: 0
Views: 85
Reputation:
You don't declare the type of the myNumber
argument to your function, so it's assumed to be an int
. You then go on to pass it to a scanf
which expects it to be a double
, and all kinds of bad things end up happening.
In this case, it's not clear why myNumber
is an argument at all -- it certainly doesn't affect what the function does at all. You probably mean to just declare it as a local variable:
long double ObtainNumber(void)
{
long double myNumber;
scanf("%lf", &myNumber);
...
By the by, long double
is unlikely to be the type you actually want. It's a kind of funky extended-precision type which can vary in size based on the architecture, compiler, and system you're working with. (ref) It's rarely used, nor necessary. double
is easier to type, and more likely to behave the way you expect.
Upvotes: 2
Reputation: 726987
long double ObtainNumber (/* you have no type name here */myNumber)
Unless you specify a type of myNumber
, its type is assumed to be int
. When you pass a pointer to int
to scanf
for the %lf
specifier, you get undefined behavior.
You need to specify the type of myNumber
to be double
long double ObtainNumber (double myNumber)
Note that this is not going to let you pass the value of myNumber
back to the caller: the value will be set in a parameter which is passed by value; it will be discarded as soon as the function exits.
If you need to return the value from the function, you need to pass a pointer to myNumber
:
long double ObtainNumber (double *myNumberPtr)
Upvotes: 2