user8755940
user8755940

Reputation:

Passing by reference with pointers

I'm writing a simple program to calculate the surface area and volume of a cylinder. Instead of writing all my code in main(), I'm using 3 functions.

The first function reads the input data of height and radius, passing the values back to the main program.

The second function uses the arguments height and radius to calculate the values of area and volume, passing each one back to the main program.

The third function uses the arguments area and volume in a print statement.

#include<stdio.h>
#define PI 3.14159 

static void inputData(double *ph, double *pr);
static void computeResults(double h, double r, double *pa, double *pv);
static void displayAnswer(double a, double v);

main()
{
    double h,r,a,v;

    inputData(&h, &r);
    computeResults(h, r, &a, &v);
    displayAnswer(a, v);

    return;
}

static void inputData(double *ph, double *pr)
{
    printf("Height: ");
    scanf("%g", ph);
    printf("Radius: ");
    scanf("%g", pr); 
}

static void computeResults(double h, double r, double *pa, double *pv)
{
    *pa = (2 * PI * h * r);
    *pv = (PI * h * r * r);
}

static void displayAnswer(double a, double v)
{
    printf("The Area is: %f", a);   
    printf("The Volume is: %f", v);
}

I'm having an issue with the scanf lines in the inputData functions.

Error message:

surfaceAreaCylinder.c:22:8: warning: format ‘%g’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=] scanf("%g", ph); ^

surfaceAreaCylinder.c:24:8: warning: format ‘%g’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=] scanf("%g", pr);

I have a fundamental understanding of pointers, and know that scanf must return the information to the caller, therefore the arguments after the control string must use call by reference. Please help me understand!

Upvotes: 0

Views: 140

Answers (2)

Thomas Holle
Thomas Holle

Reputation: 11

In the scanf lines in your inputData(double*, double*) function, you have specified the format strings as "%g". This format string is used for single precision floating point numbers, which means that your calls to scanf require pointers to float as their second argument.

You have two options.

  1. use "%lf" as the format string in your calls to scanf i.e. scanf("%lf", ph);
  2. change double to float

Wikipedia has a pretty good breakdown on the available format strings: https://en.wikipedia.org/wiki/Scanf_format_string#Format_string_specifications

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35164

"%g" is for datatype float, but you provide an argument of type double. Use "%lg" instead. For more details, confer, for example, scanf reference at cppreference.com.

Upvotes: 4

Related Questions