将结构指针或数组作为函数参数传递

Passing Struct Pointer or Array as Function Argument

我有一个像这样的 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 缓冲区做一些事情。

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

这里也一样。即使是指向 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。