如何使用指针变量

时间:2016-11-10 21:44:12

标签: c pointers

我正在关注我正在阅读C的一本书,并且想知道是否有人可以帮我解决我遇到的问题。我的函数必须允许用户输入浮点数,然后该数字必须存储在指针参数指向的变量中。当我在main中打印值时,我会不断变为零。该函数只允许返回true或false,因此我无法实际返回该值。这是我的代码:

只是寻求指导,谢谢!

#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;
}

1 个答案:

答案 0 :(得分:1)

pNumber = &number;只将您的局部变量的地址存储在函数的参数中(也是一个局部变量)

您要做的是:*pNumber = number;

BTW你可以直接做:if (sscanf_s(record, "%lf", pNumber) != 1)

您的main可以大大简化并且更加安全:

int main(void) 
{
    double d1;

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

修正:

  • 不必要的临时变量
  • 打印双重
  • 的格式错误
  • 没有测试输入是否有效