【发布时间】:2015-05-03 01:47:21
【问题描述】:
在我必须参加期末考试之前,我正在努力理解我的作业。我试图了解我到底在声明什么。
所以在给定的文件中,typedef struct 的声明如下:
(结构声明)
/** The following two structs must be defined in your <gamename>.c file **/
typedef struct game_position_t *game_position;
/* move struct must code enough information to reverse the move, given the resulting position */
typedef struct move_t *move;
然后我就这样构建了结构(是的,这必须分开,因为它是接口编程):
(结构定义)
/** The following two structs must be defined in your <gamename>.c file **/
struct game_position_t {
int mathy;
int numrows;
int *sizes;
};
/* move struct must code enough information to reverse the move, given the resulting position */
struct move_t {
int rownum;
int move_size;
};
那么game_position的函数和声明的例子例如是:
(示例函数)
/* return the starting position, NULL if error */
game_position starting_position(int me_first, int argc, char **argv) {
if (argc < 3) {
printf("\n\nToo few arguments, see help below\n\n");
game_help(argv[0]);
return NULL;
}
int mathy;
if (strcmp(argv[2],"search")==0)
mathy = 0;
else if (strcmp(argv[2],"mathy")==0)
mathy = 1;
else {
printf("\n\nSecond argument must be \"search\" or \"mathy\", see help below\n\n");
game_help(argv[0]);
return NULL;
}
int play_default = (argc==3);
if (play_default) printf("\n\nOK, we will play the default game of 7 5 3 1\n\n");
int defaultgame[4] = {7,5,3,1};
game_position result = malloc(sizeof(struct game_position_t)*1);
result->mathy = mathy;
if (result) {
result->numrows = (play_default ? 4 : argc-3);
result->sizes = malloc(sizeof(int)*(result->numrows));
int row;
for (row=0; row<(result->numrows); row++)
(result->sizes)[row] = (play_default ? defaultgame[row] : strlen(argv[row+2]));
}
return result;
}
所以我的主要误解是当以这种方式使用结构声明时,特别是将* 放在这样的名称之前,typedef struct move_t *move;。上一行是说将其移动为结构指针还是取消引用移动?从那继续。在定义它们时,我只使用结构名称,例如struct move_t。我不完全理解它们是如何联系在一起的以及在什么问题上。然后在函数内部我只是声明了game_position,但仍然需要使用解引用器'p->`来访问它的字段。因此,如果有人可以向我解释这些结构变量何时指向结构以及它们何时是实际结构。
我误解的一个例子是在声明结果之后的示例函数中。我首先想到使用. 运算符来访问和设置它的字段。然后由于编译器错误而更改了它,但现在我想了解我的误解。为什么我必须 malloc game_position_t 而不是 game_position?
【问题讨论】: