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

时间:2018-10-17 22:41:32

标签: c function struct typedef

我有一个像这样的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缓冲区进行填充。

2 个答案:

答案 0 :(得分:6)

# [[ 1 0 0] ┌ a # [ 1 1 0] ├ b # [ 6 4 2] <─┴ output / current line # [16 12 6] # [46 34 18]] def compute(x): a = x[0] b = x[1] return (a + b + 1) * 2 必须在引用该类型的函数原型之前。 C代码是按顺序处理的,在定义名称之前您不能引用它。因此,如果您首先没有结构定义,那么它会认为typedef是一个已声明的变量,但是它之前需要类型说明符。

答案 1 :(得分:0)

这里也一样。甚至带有指向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。