C、编译器错误和指针

C, Compiler-Error and Pointers

本文关键字:指针 错误 编译器      更新时间:2023-10-16

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

#include <stdio.h>
void sgnFunction(float *input[], float *weight[])
{
    printf("VALUES: %.2f %.2f %2.f, WEIGHTS: %.2f, %.2f, %.2fn", *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, %.2fn", 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 *'

我不明白修复它意味着什么。我知道我可能只是在使用指针时搞砸了一些东西。对问题所在、我的指针做错了什么以及如何解决此问题的良好解释将不胜感激。

如果你像这样调用函数

 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, %.2fn", input[0], input[1], input[2], weight[0], weight[1], weight[2]); // here also
}
sgnFunction(&x, &w);

问题是您正在传递类型为 float ** 的指针地址。就做——

sgnFunction(x, w);

x属于 float * 型。因此,执行&x将生成类型为 float ** 的指针的地址。

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

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

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

你不是说:void sgn函数(浮点*输入,浮点*权重(

浮点数 *a[] 实际上是浮点数 **a

关键是,在 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,

在评估时,*输入[0]

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

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