简体   繁体   English

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

[英]Passing Struct Pointer or Array as Function Argument

I have a typedef struct like so: 我有一个像这样的typedef结构:

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

I'm trying to pass an array of type move_t to a function as a sort-of buffer to be filled... like so: 我试图将类型为move_t的数组move_t给函数作为要填充的排序缓冲区...如下所示:

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

or 要么

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

Both generate an obscure gcc error: 两者都会产生模糊的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

I've tried removing the typedef and just making it a normal struct, etc... all result in similar errors. 我试过删除typedef并使其变成普通的结构,等等...所有这些都会导致类似的错误。 Feels basic, I know I'm missing something... 感觉很基本,我知道我想念一些东西...

My function prototype and implementation's signature absolutely match... so that part of the error is even stranger. 我的函数原型和实现的签名完全匹配...因此错误的一部分甚至更陌生。

My goal is to make an array of move_t , then pass it into this function to be populated with move_t 's. 我的目标是制作一个move_t数组,然后将其传递到此函数中,以使用move_t填充。 The caller then does stuff with the populated move_t buffer. 然后,调用者使用已填充的move_t缓冲区进行填充。

The typedef needs to be before the function prototype that refers to the type. typedef必须引用该类型的函数原型之前 C code is processed in order, you can't refer to a name before it's defined. C代码是按顺序处理的,在定义名称之前您不能引用它。 So if you don't have the structure definition first, then it thinks move_t is a variable being declared, but it needs a type specifier before it. 因此,如果您首先没有结构定义,那么它会认为move_t是要声明的变量,但是它之前需要类型说明符。

Same here. 同样在这里。 Even the declaration with pointer to move_t is not a problem. 甚至带有指向move_t指针的声明也不是问题。

Did you make sure your declaration is complete, before it is being used to declare a function prototype? 在用于声明函数原型之前,您是否确保声明已经完成?

Here is the sample code using your typedef and pointer based declaration: 这是使用基于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;
}

compiled move.c with gcc. 用gcc编译move.c。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM