Micah
Micah

Reputation: 273

Simple C Program Causing Segmentation Fault

I am just learning C and I am trying to write a simple program to do a simple calculation. The program compiles just fine, however when I enter values and attempt to run it, I get "Segmentation Fault". Can someone please help me understand why this is happening and what exactly a segmentation fault is?

Code:

#include <stdio.h>

float main()
{
  int price, service;
  float annual, value;

  printf("Enter the purchase price, years of service, annual depreciation:\n");
  scanf("%d %d %f\n", price, service, annual);

  value = (annual * service) - price;

  printf("The salvage value of the item is %f", value);
  return 0;
}

Any and all help is greatly appreciated! Thanks!

Upvotes: 1

Views: 711

Answers (3)

verbose
verbose

Reputation: 7917

You have two problems with your program. First, main() should return an int, typically zero for success and some other value for failure. Change float main () to int main() and see if that makes a difference.

Second, as the other two answers have pointed out, your arguments to scanf() should be the addresses of the variables that will hold the input values:

scanf("%d %d %f\n", &price, &service, &annual);

Upvotes: 2

haccks
haccks

Reputation: 106102

Change

scanf("%d %d %f\n", price, service, annual);

to

scanf("%d %d %f", &price, &service, &annual);

because scanf always expect a pointer as its argument. Also remove \n from format specifier of scanf() Also change float main() to int main().

Upvotes: 1

DGomez
DGomez

Reputation: 1480

This is wrong

 scanf("%d %d %f\n", price, service, annual);

should be:

 scanf("%d %d %f\n", &price, &service, &annual);

Upvotes: 3

Related Questions