bodotheguy bodotheguy - 28 days ago 8
C Question

How to store variable with pointer variable

I am following along with a book i am reading on C and was wondering if anyone could help me out with an issue i am having. My function must allow the user to enter a floating point number and then that number must be stored in the variable that is being pointed to by the pointer parameter. When i print the value in main i keep getting zeros. The function is only allowed to return true or false so i cant actually return the value. Here is my code:

Just looking for guidance, thanks!

#include <stdio.h>
#include <stdbool.h>
#pragma warning(disable: 4996)




bool getDouble(double *pNumber);


int main(void)
{
double d1 = 0;
double *pNumber;
bool i;


pNumber = &d1;
i = getDouble(pNumber);
printf("%f", *pNumber);



}


/*
* Function: getDouble()Parameter: double *pNumber: pointer
* to a variable that is filled in by the user input, if
* valid
* Return Value: bool: true if the user entered a valid
* floating-point number, false otherwise
* Description: This function gets a floating-point number
* from the user. If the user enters a valid floating-point
* number, the value is put into the variable pointed to by
* the parameter and true is returned. If the user-entered
* value is not valid, false is returned.
*/
bool getDouble( double *pNumber )
{

/* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
char record[121] = { 0 }; /* record stores the string */
double number = 0.0;
/* NOTE to student: indent and brace this function consistent with your others */
/* use fgets() to get a string from the keyboard */
fgets(record, 121, stdin);
/* extract the number from the string; sscanf() returns a number
* corresponding with the number of items it found in the string */
if (sscanf_s(record, "%lf", &number) != 1)
{
/* if the user did not enter a number recognizable by
* the system, return false */
return false;
}
pNumber = &number; /* this is where i think i am messing up */
return true;
}

Answer

pNumber = &number; just stores the address of your local variable in the parameter of your function (which also is a local variable)

What you want to do is: *pNumber = number;

BTW you can directly do: if (sscanf_s(record, "%lf", pNumber) != 1)

And your main could be greatly simplified and made safer:

int main(void) 
{
    double d1;

    pNumber = &d1;
    if (getDouble(&d1))
    {
       printf("%lf", d1);
    }
}

Fixes:

  • unnecessary temp variables
  • wrong format to print the double
  • no test to see if input is valid