Lars Honeytoast
Lars Honeytoast

Reputation: 29

segmentation fault with scanf and pointers

I'm very new to C so the solution is probably trivial but I can't seem to figure this out. I get a segmentation fault when I run getDemensions() in my program:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void getDemensions(double *, double *);
void calculateAreaAndCircumference(double, double, double *, double *);
void displayRectangleInformation(double, double, double, double);

int main() {
  double length, width, area, circumference;

  getDemensions(&length, &width);

  calculateAreaAndCircumference(length, width, &area, &circumference);

  displayRectangleInformation(length, width, area, circumference);
}

void getDemensions(double *length, double *width) {
  printf("Enter rectangle length: ");
  scanf("%lf", *length);
  printf("Enter rectangle width: ");
  scanf("%lf", *width);
}

Also worth noting: I've tried using "&" in front of the variables in the scanf() with no segmentation fault, but the input is not saved.

Upvotes: 2

Views: 259

Answers (1)

John Bupit
John Bupit

Reputation: 10618

scanf expects a pointer. Since length and width are pointers already, you simply pass them to scanfs:

void getDemensions(double *length, double *width) {
    printf("Enter rectangle length: ");
    scanf("%lf", length);
    printf("Enter rectangle width: ");
    scanf("%lf", width);
}

Upvotes: 5

Related Questions