【问题标题】:C, Compiler-Error and PointersC、编译器错误和指针
【发布时间】:2013-10-09 15:17:51
【问题描述】:

我在传递浮点数组时遇到了一些麻烦。 我将一些浮点数组放入 ActivationFunc,然后从那里将这些相同的数组放入 sgnFunction,由于某种原因最终会产生不同的值。

#include <stdio.h>
void sgnFunction(float *input[], float *weight[])
{
    printf("VALUES: %.2f %.2f %2.f, WEIGHTS: %.2f, %.2f, %.2f\n", *input[0], *input[1], *input[2], *weight[0], *weight[1], *weight[2]);
}

void ActivationFunc(float *x, float *w, float *n, int *d)
{
    printf("VALUES: %.2f %.2f %2.f, WEIGHTS: %.2f, %.2f, %.2f\n", x[0], x[1], x[2], w[0], w[1], w[2]);
    sgnFunction(&x, &w);
}

int main()
{
    float x1[3] = {1, 0, 1};
    float x2[3] = {0, -1, -1};
    float x3[3] = {-1, -0.5, -1};
    int d[3] = {0, 1, 1};
    float w[3] = {1, -1, 0};
    float n = 0.1;

    ActivationFunc(x1, w, &n, &d[0]);
}

如果我从“sgnFunction(&x, &w);”中删除“&”,我会收到以下编译器错误:

test.c: In function 'ActivationFunc':
test.c:10:9: warning: passing argument 1 of 'sgnFunction' from incompatible pointer type
test.c:2:14: note: expected 'float **' but argument is of type 'float *'

我不明白修复它意味着什么。 我知道我可能只是在使用指针搞砸了一些事情。一个很好的解释是什么错了,我的指针做错了什么,以及如何解决这个问题,我们将不胜感激。

【问题讨论】:

    标签: c++ c arrays pointers parameter-passing


    【解决方案1】:

    如果你这样调用函数

     sgnFunction(x, w);  
    

    你的定义应该是

    void sgnFunction(float *input, float *weight) // you just need to change array of pointers to single pointer 
    {
        printf("VALUES: %.2f %.2f %2.f, WEIGHTS: %.2f, %.2f, %.2f\n", input[0], input[1], input[2], weight[0], weight[1], weight[2]); // here also
    }
    

    【讨论】:

    • 啊...我有一个误解,我必须以类似于 C# 或 Java 语法的方式传递它。指针只是指针——我应该记住这一点。谢谢!
    【解决方案2】:
    sgnFunction(&x, &w);
    

    问题是您正在传递float ** 类型的指针地址。做吧-

    sgnFunction(x, w);
    

    x 的类型为 float *。因此,执行&amp;x 将产生float ** 类型的指针的地址。

    此外,传递一个数组将衰减到指向数组中第一个元素的指针。所以将函数签名更改为 -

    void sgnFunction(float *input, float *weight);
    

    【讨论】:

    • 我在我的代码下面声明:“如果我从 "sgnFunction(&x, &w);" 中删除 '&',我会收到以下编译器错误:...”
    • float *, float **, float *[N] 都是不同的类型。
    【解决方案3】:

    void sgnFunction(float *input[], float *weight[])

    你不是说: void sgnFunction(float *input, float *weight)

    float *a[] 实际上是一个 float **a

    【讨论】:

      【解决方案4】:

      关键是,在c中,数组下标运算符的优先级高于取消引用运算符。因此,表达式 *input[0] 将被评估为 *(input[0])。

      考虑声明,

      int a[3][4] = { {1, 2 ,3}, {4, 5, 6} };

      这里'a'是一个二维数组,'&a[0][0]'投影第一个元素的地址,'a[0]'投影第一行的地址,'a'投影第一个元素的地址数组的基地址。如果您在上述所有三种情况下都打印地址,您将得到相同的值,但地址的性质不同。情况1,地址指向一个元素,情况2,地址指向一行元素,情况3,地址指向整个数组。

      在你的函数中,sgnFunction,

      在评估时,*input[0],它被评估为 *(input[0]) 这指的是“输入”的第一行,即“x”,因此您的值与预期的一样。但是在评估 input[1] ((input[1])) 时,这是指“输入”的第二行。但是没有第二排。因此垃圾价值。要解决此问题,请将 *input[1] 更改为 (*input)[1]。

      附带说明,在调用函数 sgnFunction 时,使用按值调用而不是按引用调用就足够了。

      【讨论】:

        猜你喜欢
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 2012-07-01
        • 2011-01-16
        相关资源
        最近更新 更多