[英]How to use pointers to return multiple values from a function in C
我目前正在編寫一個用於分類的程序,該程序需要使用功能來使用戶能夠輸入3個可變項。 我很難將這些變量返回到我的主函數中,我曾經遇到過其他類似的問題,並且曾嘗試使用指針,但無法使其正常工作。 我的嘗試如下:
#include <stdio.h>
#include <stdlib.h>
//Function Header for positive values function
double get_positive_value(double* topSpeed, double* year, double*
horsepower);
int main(void){
int reRunProgram = 0;
while (reRunProgram==0)
{
//variable declarations
double tS;
double yR;
double hP;
int menuOption;
int menuOption2;
//menu
printf("1.Create Bugatti\n");
printf("2.Display Bugatti\n");
printf("3.Exit\n");
//user choice
scanf("%d", &menuOption);
//Create car
if (menuOption == 1) {
//run the get positive values function
get_positive_value (&tS, &yR, &hP);
printf("top speed is %lf\n", tS);
}
//Display car (but no car created)
else if (menuOption == 2){
printf("error no car created\n");
}
//Exit
else if (menuOption ==3){
exit(EXIT_FAILURE);
}
}
return 0;
}
double get_positive_value(double* topSpeed, double* year, double*
horsepower)
{
do {
printf("Please enter the top speed of the bugatti in km/h\n");
scanf("%lf", &topSpeed);
} while(*topSpeed<=0);
do{
printf("Please enter the year of the bugatti, in four digit form (e.g. 1999)\n");
scanf("%lf", &year);
} while(*year<=0);
do{
printf("Please enter the horsepower of the bugatti\n");
scanf("%lf", &horsepower);
} while(*horsepower<=0);
}
除非將它們包裝在struct
否則無法從函數返回多個值。 就指針而言,您可以修改從main傳遞給函數的值。 我認為您在這里做錯了:
scanf("%lf", &topSpeed);
由於topSpeed
是指向double的指針,因此您只需要傳遞從main傳遞的變量的地址(而不是指針變量的地址)。 您應該改為:
do {
printf("Please enter the top speed of the bugatti in km/h\n");
scanf("%lf", topSpeed);
} while(*topSpeed<=0);
do {
printf("Please enter the year of the bugatti, in four digit form (e.g. 1999)\n");
scanf("%lf", year);
} while(*year<=0);
do {
printf("Please enter the horsepower of the bugatti\n");
scanf("%lf", horsepower);
} while(*horsepower<=0);
我希望這有幫助。
你聲明的變量tS
, yR
及hP
內main
功能,並通過參考傳遞他們get_positive_value()
函數。
因此,正在傳遞變量的地址 。 不是變量本身。
instead. 在get_positive_value()
,您嘗試使用scanf()
將一些值放入3個變量中,在此應給定變量的但應給定 。 get_positive_value()
&topSpeed
get_positive_value()
中的&(&tS)
main()
。
既然你已經按引用傳遞它們, get_positive_value()
你有地址tS
, yR
, hP
在topSpeed
, year
, horsepower
分別。
topSpeed
本身就是tS
的地址。 不是&topSpeed
。
你應該改變
scanf("%lf", &topSpeed);
至
scanf("%lf", topSpeed);
(對於其他2個變量同樣如此)
因為topSpeed
在main()
具有變量tS
的地址。 因此,如果您說&topSpeed
,則嘗試訪問' tS
地址的地址'。
當您執行*someptr
您正在詢問該指針指向的內存地址的值。
當您執行scanf
並將&x
用作變量時,您之所以這樣做是因為要將值存儲在該內存地址中。 因此,當使用指針執行scanf
時,不要使用*
因為您傳遞的是值(而不是地址)來存儲值。
您也不使用&
,因為您傳遞的是指針的內存地址,而不是實際要修改的地址。 這是您的主要錯誤。 最后,您可以使用struct
一次return
所有這些值,但是指針更加優雅。
希望我能幫到您,我很清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.