1

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!

Wooble
  • 87,717
  • 12
  • 108
  • 131
Micah
  • 263
  • 1
  • 5
  • 14

3 Answers3

3

This is wrong

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

should be:

 scanf("%d %d %f\n", &price, &service, &annual);
DGomez
  • 1,450
  • 9
  • 25
2

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);
verbose
  • 7,827
  • 1
  • 25
  • 40
1

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().

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Thank you for your help, this was the problem! I guess the segmentation fault is because of the pointers? – Micah Sep 08 '13 at 01:54
  • Yes. This is mainly because of the missing `&` here in `scanf` arguments. `scanf` always expects a pointer (address) as its argument – haccks Sep 08 '13 at 02:07