c - 理解 C 中的指针结构

标签 c pointers struct

在我必须参加期末考试之前,我试图理解我的作业。我试图理解我到底在声明什么。 所以在给定的文件中,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;

然后我就这样构建了结构(是的,这必须分开,因为它是接口(interface)编程):

(结构定义)

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

关于c - 理解 C 中的指针结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009405/

相关文章:

c - 在 fscanf 中添加多个参数

c++ - 不理解编译器的行为

c - 将数组转换为结构时的数据顺序

c - 这段代码如何在 gcc 中编译,它实际上在做什么?

c++ - 将 va_list 传递给只接受变量参数的 #define (...)

c++ - c++中的唯一/智能指针 vector

c - feof(FILE *) 内置函数中的段错误

c++ - 无法将结构类型的元素添加到 vector 中?

c - 用C读取二进制文件

c - 为什么动态分配 char** 和 char* 类型会使用 malloc 段错误?