简体   繁体   中英

Passing Struct Pointer or Array as Function Argument

I have a typedef struct like so:

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:

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:

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. 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. The caller then does stuff with the populated move_t buffer.

The typedef needs to be before the function prototype that refers to the type. C code is processed in order, you can't refer to a name before it's defined. 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.

Same here. Even the declaration with pointer to move_t is not a problem.

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:

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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