为什么我需要在 C 中指定引用和指针而不是普通变量
Why do I need to specify references and pointers instead of plain variables in C
如果所有引用和指针都简化为纯变量,究竟是什么阻止了编译器理解以下程序?
/* Takes three numbers as input and returns their sum and average as output */
#include <stdio.h>
void sum_n_avg(double arg1, double arg2, double arg3, double
*sum, double *avg);
int main(){
double one, two, three, sum, avg;
printf("Enter three numbers> ");
scanf("%lf%lf%lf", &one, &two, &three);
sum_n_avg(one, two, three, &sum, &avg);
printf("%lf is the sum, %lf is the average\n", sum, avg);
}
void sum_n_avg(double arg1, double arg2, double arg3, double *sum, double *avg){
*sum = arg1 + arg2 + arg3;
*avg = (*sum) / 3;
}
这个问题不是"how do I do the thing"而是"why does C do this thing?"
这里的任何直觉都会非常有帮助 - 指向其他讨论(如 "why use pointers" 或 "when to use pointers" 的链接不是我要找的。
sum_n_avg()
有 5 个输入:3 个是 double
,2 个是指针。
void sum_n_avg(double arg1, double arg2, double arg3, double *sum, double *avg);
除了指示数据存储位置的 2 个指针外,该函数没有其他信息。
What exactly is stopping the compiler from understanding the following program if all references and pointers were reduced to just plain variables?
如果从 sum_n_avg()
中删除 "references",则
sum_n_avg_noref(double arg1, double arg2, double arg3, double sum, double avg)
是一个需要 5 double
个输入的函数。
函数中没有任何信息,也没有指示参数应该是除 "input" 之外的任何内容。
why does C do this thing
C因为简单的设计而成功。函数参数是输入。 return 值是输出。
引用复杂的东西。
为了容纳多个输出,代码传入指针作为存储数据的位置。
如果所有引用和指针都简化为纯变量,究竟是什么阻止了编译器理解以下程序?
/* Takes three numbers as input and returns their sum and average as output */
#include <stdio.h>
void sum_n_avg(double arg1, double arg2, double arg3, double
*sum, double *avg);
int main(){
double one, two, three, sum, avg;
printf("Enter three numbers> ");
scanf("%lf%lf%lf", &one, &two, &three);
sum_n_avg(one, two, three, &sum, &avg);
printf("%lf is the sum, %lf is the average\n", sum, avg);
}
void sum_n_avg(double arg1, double arg2, double arg3, double *sum, double *avg){
*sum = arg1 + arg2 + arg3;
*avg = (*sum) / 3;
}
这个问题不是"how do I do the thing"而是"why does C do this thing?"
这里的任何直觉都会非常有帮助 - 指向其他讨论(如 "why use pointers" 或 "when to use pointers" 的链接不是我要找的。
sum_n_avg()
有 5 个输入:3 个是 double
,2 个是指针。
void sum_n_avg(double arg1, double arg2, double arg3, double *sum, double *avg);
除了指示数据存储位置的 2 个指针外,该函数没有其他信息。
What exactly is stopping the compiler from understanding the following program if all references and pointers were reduced to just plain variables?
如果从 sum_n_avg()
中删除 "references",则
sum_n_avg_noref(double arg1, double arg2, double arg3, double sum, double avg)
是一个需要 5 double
个输入的函数。
函数中没有任何信息,也没有指示参数应该是除 "input" 之外的任何内容。
why does C do this thing
C因为简单的设计而成功。函数参数是输入。 return 值是输出。
引用复杂的东西。
为了容纳多个输出,代码传入指针作为存储数据的位置。