【问题标题】:How to pass the pointer values from a separate function back to main using a structure如何使用结构将指针值从单独的函数传回主函数
【发布时间】:2016-10-14 18:13:15
【问题描述】:
#include <stdio.h>
#define G 9.81

//结构带来的使用被称为USER_INPUT

typedef struct
{
    double weight;
    double drag;
    double time;

} USER_INPUT;

void getInput(USER_INPUT *); //function prototype - which i think works

void main()

{
    USER_INPUT input;
    getInput(&input);

//这是输入值应该显示的地方,但它不会返回任何内容

    printf("Weight = ", input.weight);
    printf("Drag = ", input.drag);
    printf("Time =", input.drag);


}

//我从用户那里获取输入的单独函数。它可以工作,但值不会传递回 main

void getInput (USER_INPUT *inpPtr)
{
    printf("Please enter the weight:");
    scanf("%lf", &inpPtr->weight);
    fflush(stdin);
    printf("Please enter the drag:");
    scanf("%lf", &inpPtr->drag);
    fflush(stdin);
    printf("Please enter the time:");
    scanf("%lf", &inpPtr->time);
    fflush(stdin);
    return(0); //<- idk if this is right either

}

【问题讨论】:

  • 不正确,如果返回类型为void,则不允许返回值。您的问题是您的 printfs 不正确。 ideone.com/f3BqOC

标签: c arrays pointers structure return-value


【解决方案1】:

您描述的问题可归因于您在printf() 语句中遗漏了格式说明符。此外,您尝试显示.drag 两次:

printf("Weight = %g\n", input.weight);
printf("Drag = %g\n", input.drag);
printf("Time = %g\n", input.time);

函数getInput() 不会将值传回main()(毕竟它的返回类型是void!),但它会修改存储在USER_INPUT 结构@987654328 的字段中的值@ 存在于main() 的范围内。

这里还有一些其他问题。 main() 函数总是返回一个int,你应该这样声明它:

int main(void){}

或者,如果您使用命令行参数,您可以这样做:

int main(int argc, char *argv[]){}

或:

int main(int argc, char **argv){}

刷新输入流是未定义的行为,尽管它适用于某些系统。为了便携性,最好不要这样做。你可以使用类似的东西:

while (getchar() != '\n')
    continue;

在调用 scanf() 后丢弃输入流中不需要的字符。

最后,返回类型为void 的函数不需要return 语句,尽管有些人喜欢使用return ; 来明确返回。但是,从这样的函数返回 int 值肯定是错误的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多