【问题标题】:Compiler Warning Passing array of structs (itself member of struct) to Function编译器警告将结构数组(结构本身的成员)传递给函数
【发布时间】:2015-01-17 17:41:30
【问题描述】:

我定义了以下结构 - 坐标结构本身就是父结构的成员

typedef struct _coord {
    double x;   // time axis - seconds rather than samples
    double y;
}   t_coord;

typedef struct _algosc {                    
    t_coord coords[COORD_COUNT];        
    //... struct continues beyond this but...
}   t_algosc;

我创建一个指向父结构的指针,然后分配内存。 object_alloc 是一个 malloc 类型函数,专用于在别处定义的 API (MAX5)。这一切正常,所以我不包括细节。

static t_class *algosc_class;   // pointer to the class of this object

    t_algosc *x = object_alloc(algosc_class)

这是我希望向其传递坐标结构数组的函数的声明

    void    au_update_coords(t_coord (*coord)[])

我将数组传递给函数如下,

au_update_coords(x->coords);

一切正常,但我收到编译器警告

1>db.algosc~.c(363): warning C4047: 'function' : 't_coord (*)[]' differs in levels of indirection from 't_coord [4]'
1>db.algosc~.c(363): warning C4024: 'au_update_coords' : different types for formal and actual parameter 1

我无法找出传递结构的正确方法。任何人都可以帮忙。也只是为了我的启迪,我冒着什么样的风险让它保持原样?

【问题讨论】:

  • 您的示例声明采用七个参数,但您调用该函数时只有一个参数。我认为这是由于为您的问题删除不必要的代码时不完整的传递造成的?请更正。
  • 数组自然衰减为指针,因此不需要传递指向数组的指针,只需传递数组本身(您现在就这样做),这当然必须反映在函数参数声明中(即删除指针声明)。
  • 谢谢 ruakh - 是的,现在更正了。
  • 感谢 Joachim - 非常清楚,如果已将其作为答案发布,我会选择它作为答案。
  • 这一行:'void au_update_coords(t_coord (*coord)[])' 正在传递一个指向 t_coord 类型的指针数组。我怀疑这不是你真正想要做的。建议:'void au_update_coords(t_coord *coord)' 你可能想要传递第二个参数,指示坐标数组中的条目数

标签: c arrays pointers struct


【解决方案1】:

你需要传递一个指向数组的指针,所以你需要把你的数组的地址变成一个指向数组的指针,this

au_update_coords(x->coords, otherArguments ...);

应该变成

au_update_coords(&x->coords, otherArguments ...);

但你不需要那个。如果您担心函数不会原地更改数组,请不要担心它会,您需要将函数签名从

void    au_update_coords(t_coord (*coord)[], otherArguments ...)

void    au_update_coords(t_coord *coord, otherArguments ...)

并像中一样直接传递数组

au_update_coords(x->coords, otherArguments ...);

当然,无论您在何处访问数组,您都可能需要修复 au_update_coords() 函数。

【讨论】:

  • x->coords 不是变长数组,它有固定维度COORD_COUNT。(结构不能包含VLA)
  • @iharob 不,不是;指向 VLA 的指针看起来像 T (*ptr)[n]。这与 T (*ptr)[] 不同,后者是指向不完整数组类型的指针。
  • 谢谢马特 - 我没有发现那个细节。好点子。 Iharob,如果您可以删除对 VLA 的引用,我会将其保留为选定答案,否则这会误导其他任何发现它的人..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
相关资源
最近更新 更多