Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

c - Defining an array of a set size in header file

I want to define a pointer to an character array of a set value in a header file. Essentially - I want to declare a chessboard in a header file.

Would something like this work, or should I be using #define? Thank you.

#ifndef myHeader
#define myHeader

typedef *char[8][8] Chessboard;

#endif

EDIT:

I have to admit I'm practicing for an upcoming test and this is just an old assignment (from one of the previous tests). After some thought and study on how header files behave, I've found that

char array[8][8]; 
char*** Chessboard = (char***) malloc (sizeof (char**)); 
*(Chessboard) = array; 

could work - however, I'm supposed to declare a type, and don't know how to do this.

To clarify - I want to define a type "Chessboard", that is a pointer to an 8x8 array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I want to define a type "Chessboard", that is a pointer to an 8x8 array.

// .h
typedef char (*Chessboard_T)[8][8];
extern Chessboard_T Chessboard_Var;

// .c
static char board[8][8];
Chessboard_T Chessboard_Var = &board;

// Usage example
void foo() {
   (*Chessboard_Var)[0][4] = 'K';
}

Hiding pointers in typedefs is usually frown upon.


A more common solution to capture the state would employ Chessboard as a structure. Example:

// Chessboard.h
typedef struct {
  char board[8][8];
  unsigned move_count;
  int en_pass;
  int castle;
  int *history;
  // etc.
} Chessboard;

// Various functions that operate with a Chessboard
Chessboard *Chessboard_Create(void);
Chessboard_Destroy(Chessboard *cb);
Chessboard_This(..);  
Chessboard_That(..);
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...