c - How to store variable with pointer variable -


i following along book reading on c , wondering if me out issue having. function must allow user enter floating point number , number must stored in variable being pointed pointer parameter. when print value in main keep getting zeros. function allowed return true or false cant return value. here code:

just looking 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;     = getdouble(pnumber);     printf("%f", *pnumber);    }   /* * function: getdouble()parameter: double *pnumber: pointer  * variable filled in user input, if  * valid * return value: bool: true if user entered valid  * floating-point number, false otherwise  * description: function gets floating-point number  * user. if user enters valid floating-point  * number, value put variable pointed  * parameter , true returned.  if user-entered  * value not valid, false returned. */ bool getdouble( double  *pnumber ) {      /* array 121 bytes in size; we'll see in later lecture how can improve code */     char record[121] = { 0 }; /* record stores string */     double number = 0.0;     /* note student: indent , brace function consistent others */     /* use fgets() string keyboard */     fgets(record, 121, stdin);     /* extract number string; sscanf() returns number     * corresponding number of items found in string */     if (sscanf_s(record, "%lf", &number) != 1)     {         /* if user did not enter number recognizable         * system, return false */         return false;     }     pnumber = &number;   /* think messing */     return true; } 

pnumber = &number; stores address of local variable in parameter of function (which local variable)

what want is: *pnumber = number;

btw can directly do: if (sscanf_s(record, "%lf", pnumber) != 1)

and main simplified , made safer:

int main(void)  {     double d1;      pnumber = &d1;     if (getdouble(&d1))     {        printf("%lf", d1);     } } 

fixes:

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

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -