【问题标题】:Understanding pointer structs in C理解 C 中的指针结构
【发布时间】: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

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

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

    【讨论】:

    • 谢谢。很有帮助。 sizeof(*move) 会工作吗?只是好奇。
    • @napkinsterror 如果可行,您可以尝试一下。有一本书叫Expert C Programming,可能对你有更多帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2017-03-22
    • 2021-07-14
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多