【问题标题】:How do I print this array after calling a function upon it?调用函数后如何打印该数组?
【发布时间】: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", *&deg);
}

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(&degree);

    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, &amp;coefficients); 应该是 inputCoeffs(degree, coefficients);。我认为编译器应该在该行上有一个警告,因为第二个参数的传入类型与函数定义的类型不同。如果没有,请打开编译器警告。始终注意并修复所有编译器警告。
  • 嘿,谢谢,它成功了!你能解释一下吗?因为我看到它的方式是,当我在main 中调用inputDegree 函数时,它的参数中有一个&amp;,考虑到该函数需要一个指针来传递给它。所以我想也许这就是inputCoeffs 的工作原理?
  • 区别在于degree不是指针,而coefficients已经是指针。
  • @kaylum 我的编译器发出警告a.c:30:25: warning: passing argument 2 of 'inputCoeffs' from incompatible pointer type inputCoeffs(degree, &amp;coefficients);

标签: c arrays function pointers


【解决方案1】:

在本次通话中

scanf("%d", *&deg);

写就够了

scanf("%d", deg);

目前尚不清楚为什么要分配比 degree 值大一个元素的内存。

coefficients = (double*)malloc((degree + 1) * sizeof(double));

在这种情况下,分配的数组有degree + 1 元素。

本次调用中第二个参数的类型

inputCoeffs(degree, &coefficients);

无效。应该有

inputCoeffs(degree, coefficients);

【讨论】:

  • 关于coefficients = (double*)malloc((degree + 1) * sizeof(double)); 行,我刚刚尝试删除+ 1 并且我的预期程序仍然有效。为什么呢?我提出+ 1 的原因是,例如,输入的degree 是2,多项式需要次数+ 1 = 3(A B C,如Ax^2 + Bx + C)分配的内存。
  • @PauloVictorio 如果您分配的内存少于所需的内存,则程序具有未定义的行为。它可以工作,因为 malloc 通常分配块的内存乘以段落大小。
【解决方案2】:

& 运算符用于获取指向现有变量的指针,而 * 用于取消引用指针。因此

inputCoeffs(degree, &coefficients);

没有意义,因为coefficients 已经是一个指针。输入系数 接受一个指针,这样你就可以写了

inputCoeffs(degree, coefficients);

由于 & 和 * 运算符基本上是相反的,这一行

scanf("%d", *&deg);

不是错误,但也可以写成

scanf("%d", deg);

此外,您应该在使用 malloc 时调用 free,因此请在代码末尾添加:

free(coefficients);
free(integralCoefficients);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多