【发布时间】:2020-03-01 09:50:45
【问题描述】:
以下代码块只是较大代码块的一部分。在程序中,我想找到需要用户输入的多项式的定积分。
我是 C 的新手,所以我很难尝试学习有关指针的语法。我发现它们非常令人困惑。
因此,如果您查看下面的代码块,我想打印数组coefficients 中包含的元素,以便查看输入的元素是否存储在数组中,但无济于事。程序在inputCoeffs() 函数之后终止。
#include <stdio.h>
#include <stdlib.h>
void inputDegree(int *deg) {
printf("Enter the degree of the polynomial: \n");
scanf("%d", *°);
}
void inputCoeffs(int deg, double *coeffs) {
printf("Enter the coefficients of the polynomial (A, B, C,...): \n");
for(int i = 0; i <= deg; i++) {
scanf("%lf", &coeffs[i]);
}
}
int main() {
int i;
int degree;
double lowerLimit;
double upperLimit;
double integral;
double *coefficients = NULL;
double *integralCoefficients = NULL;
inputDegree(°ree);
coefficients = (double*)malloc((degree + 1) * sizeof(double));
integralCoefficients = (double*)malloc((degree + 1) * sizeof(double));
inputCoeffs(degree, &coefficients);
for(i = 0; i <= degree; i++) {
printf("\t%lf\n", coefficients[i]);
}
return 0;
}
【问题讨论】:
-
inputCoeffs(degree, &coefficients);应该是inputCoeffs(degree, coefficients);。我认为编译器应该在该行上有一个警告,因为第二个参数的传入类型与函数定义的类型不同。如果没有,请打开编译器警告。始终注意并修复所有编译器警告。 -
嘿,谢谢,它成功了!你能解释一下吗?因为我看到它的方式是,当我在
main中调用inputDegree函数时,它的参数中有一个&,考虑到该函数需要一个指针来传递给它。所以我想也许这就是inputCoeffs的工作原理? -
区别在于
degree不是指针,而coefficients已经是指针。 -
@kaylum 我的编译器发出警告
a.c:30:25: warning: passing argument 2 of 'inputCoeffs' from incompatible pointer type inputCoeffs(degree, &coefficients);
标签: c arrays function pointers