Jon*_*cki 3 c pointers function pass-by-reference
我正在做我的 C 入门课程作业,我的任务是以下......
虽然我的知识很基础,但我相信我理解主要内容
//first and second double hold the scanf inputs
double first;
double second;
//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;
printf("Enter your first number\n");
scanf("%f\n", &first);
printf("Enter your second number\n");
scanf("%d\n", &second);
//call the function, first and second by value, &c / &d by reference - correct?
pointerIntro(first, second, &c, &d);
Run Code Online (Sandbox Code Playgroud)
对于函数...
float myFunction(double a, double b, double *c, double *d)
{
c = a/b;
d = a*b;
//printf statements
}
Run Code Online (Sandbox Code Playgroud)
如果这个问题的流程很混乱,我深表歉意,但这对我来说是过程的一部分:P
因此,对于我的正式问题 1. 在 main 中启动两个双指针变量(*c 和 *d)作为函数中的引用传递是否正确?2. 我可以通过 &c / &d 来调用带有引用指针的函数吗?3. 对这个问题还有其他批评吗?
变量“c”和“d”不必是指针即可通过引用传递它们。所以你有两种情况:
当您在主函数中将“c”和“d”定义为指针时,您将把它们传递给如下函数:pointerIntro(first, second, c, d);因为它们已经是指针,并且您不需要发送它们的引用,您只需发送它们即可。
如果您将 'c' 和 'd' 定义为双变量,double c, d;您将使用 '&' 符号通过引用将它们发送到函数,如下所示:pointerIntro(first, second, &c, &d);。
然后,在您的函数中,要实际设置“c”和“d”的值,您将需要像这样取消对它们的指针的引用*c = a/b; *d = a*b;:
如果您不熟悉,可以在此处查看取消引用指针的含义:What does “取消引用”指针意味着什么?
应该有效的代码:
#include <stdio.h>
void myFunction(double a, double b, double *c, double *d)
{
*c = a / b;
*d = a * b;
}
int main(void)
{
double a, b, c, d;
scanf("%lf", &a);
scanf("%lf", &b);
myFunction(a, b, &c, &d);
printf("%lf %lf", c, d);
}
Run Code Online (Sandbox Code Playgroud)