C、编译器错误和指针
C, Compiler-Error and Pointers
我在传递浮点数组时遇到了一些麻烦。我将一些浮点数数组放入 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} };
[0]' 投射第一行的地址,'a' 投射数组的基址。如果在上述所有三种情况下打印地址,您将获得相同的值,但地址的性质不同。在情况 1 中,地址是指一个元素,在情况 2 中,地址是指一行元素,在情况 3 中,地址是指整个数组。
在你的函数中,sgnFunction,
在评估时,*输入[0],它被评估为*(输入[0](,这是指"输入"的第一行,即"x",因此您的值符合预期。但是在评估输入[1]((input[1]((时,这是指"输入"的第二行。但是没有第二排。因此垃圾值。要解决此问题,请将 *input[1] 更改为 (*input([1]。
附带说明一下,在调用函数 sgnFunction 时,使用按值调用而不是按引用调用就足够了。
- 为什么我在空指针错误(链表)中获取成员访问权限
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 为什么我得到 munmap_chunk():无效的指针:错误
- 成员模板函数指针错误
- 删除指针时,未分配被释放的 C++ 指针错误
- Visual Studio 中的"指向引用的指针"错误不会按发生位置的文件名显示
- C++数组指针错误无法将“int*”转换为“int**”
- C++ 通过函数指针错误调用成员函数
- 从 BST 中删除元素(指针错误)
- 随机生成的多维布尔指针错误
- 在测试中使用unique_ptr时指针错误无效
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 抽象类和唯一指针 c++ 错误
- 返回函数指针错误而不带类型定义
- 练习中出现空指针错误
- 指针错误导致的分段错误(简单..)
- free():C++中的指针错误无效
- 使用布尔值数组"表达式必须具有指向对象类型的指针"错误C++
- 指针错误的C 数组