在我必须参加期末考试之前,我正在努力理解我的一项任务。我想弄清楚我到底要宣布什么。因此,在给定的文件中,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;
}因此,我的主要误解是在以这种方式使用struct声明时,特别是将*放在像这样的名称typedef struct move_t *move;之前。前一行的意思是移动它是一个结构指针还是取消引用的移动?从那继续下去。在定义它们时,我只使用结构名称(如struct move_t )。我不完全理解他们是如何联系在一起的,在什么问题上。然后在函数中我只声明game_position,但仍然需要使用去函数器‘p->’来访问它的字段,所以如果有人能向我解释一下,这些结构变量是指向结构的,什么时候是实际的结构。
我误解的一个例子是,在示例函数中,结果被声明之后。我首先考虑使用.操作符来访问和设置它的字段。然后,由于编译器错误,我更改了它,但是现在我想理解我的误解。为什么我要game_position_t而不是game_position
发布于 2015-05-03 02:06:12
typedef定义了一个类型,因此typedef struct move_t *move定义了一个名为move的新类型,它是指向struct move_t的指针类型。因此,如果您用move ptr定义了一个变量,那么ptr将有一个指针类型,因此您应该使用通过指针访问成员的语法。当然,在为它分配内存时,您必须指定结构的确切大小,而不是指针的大小,即sizeof(struct move_t)
https://stackoverflow.com/questions/30009405
复制相似问题