【问题标题】:Passing Struct Pointer or Array as Function Argument将结构指针或数组作为函数参数传递
【发布时间】:2019-03-22 16:55:40
【问题描述】:

我有一个像这样的 typedef 结构:

typedef struct {
    int col;
    int row;
} move_t;

我正在尝试将 move_t 类型的数组作为要填充的缓冲区类型传递给函数......就像这样:

void generate_valid_moves(int fc, int fr, move_t* moves, int limit);

void generate_valid_moves(int fc, int fr, move_t moves[], int limit);

两者都会产生一个不起眼的 gcc 错误:

moves.h:43: error: expected declaration specifiers or ‘...’ before ‘move_t’
moves.h:887: error: conflicting types for ‘generate_valid_moves’
moves.h:43: note: previous declaration of ‘generate_valid_moves’ was here

我已经尝试删除 typedef 并将其设置为普通结构等...都会导致类似的错误。感觉很基本,我知道我错过了一些东西......

我的函数原型和实现的签名完全匹配……所以部分错误就更奇怪了。

我的目标是创建一个move_t 的数组,然后将其传递给此函数以填充move_t。然后调用者对填充的move_t 缓冲区进行处理。

【问题讨论】:

  • @PatrickRoberts 不,他的语法正确。
  • 你确定在函数原型之前有typedef吗?
  • @Barmar 哇...我一定很累...这就是问题所在,typedef之前的函数原型...如果您写出来,我会接受答案!谢谢。
  • @Barmar 我也一定很累,我大部分时间都在用 C# 编写...

标签: c function struct typedef


【解决方案1】:

typedef 需要在引用该类型的函数原型之前。 C 代码是按顺序处理的,在定义之前不能引用名称。所以如果你没有先定义结构体,那么它会认为move_t 是一个被声明的变量,但它之前需要一个类型说明符。

【讨论】:

    【解决方案2】:

    这里也一样。即使是带有指向 move_t 的指针的声明也不是问题。

    在用于声明函数原型之前,您是否确保声明完整?

    这是使用你的 typedef 和基于指针的声明的示例代码:

    #ifndef MOVE_H_INCLDED
    #define MOVE_H_INCLUDED
    
    typedef struct {
        int col;
        int row;
    } move_t;
    
    void generate_valid_moves(int fc, int fr, move_t* moves, int limit);
    
    #endif
    
    #include <stdio.h>
    #include "move.h"
    
    void generate_valid_moves(int fc, int fr, move_t* moves, int limit)
    {
    
    }
    
    int main()
    {
        return 0;
    }
    

    用 gcc 编译 move.c。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2019-05-03
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多