理解 C 中的指针结构

Understanding pointer structs in C

我想在参加期末考试之前理解一项作业。我试图理解我到底在声明什么。 所以在给定的文件中,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;。前一行是说 move it a struct pointer 还是 dereferencing move?从那继续。在定义它们时,我只使用结构名称,例如 struct move_t。我不完全明白他们是如何联系在一起的,在什么情况下联系在一起。然后在函数内部我只是声明 game_position,但仍然需要使用解引用器 'p->` 来访问它的字段。因此,如果有人可以向我解释这些结构变量何时指向结构以及何时它们是实际结构。

我误解的一个例子是在声明结果后的示例函数中。我首先想到使用 . 运算符来访问和设置它的字段。后来因为编译器错误改了,现在想明白我的误会了。为什么我必须 malloc game_position_t 而不是 game_position?

typedef定义了一个类型,所以typedef struct move_t *move定义了一个名为move的新类型,它是一个指针类型,指向struct move_t。因此,在此之后,如果您使用 move ptr 定义变量,ptr 将具有指针类型,因此您应该使用通过指针访问成员的语法。在为其分配内存时,当然你必须指定结构的确切大小而不是指针的大小,即 sizeof(struct move_t)