实施列表 ADT 时出错 "member reference base type 'MOVE' (aka 'struct s_move *')is not a structure or union"

Error while implementing List ADT "member reference base type 'MOVE' (aka 'struct s_move *')is not a structure or union"

我正在尝试在 C 中实现 List ADT,但我在互联网上找不到太多帮助,因为看起来非常像 C++ 中的例子,我对此一无所知。我可以完全理解数据结构(至少,我想我理解了)但是我很难将它变成一个 ADT,分离文件等等。 尝试实现追加函数时,在遍历列表的循环中出现如下错误: member reference base type 'MOVE' (aka 'struct s_move *')is not a structure or union 我知道问题出在指针上并通过简化我的数据,因为这显然对我正在解决的问题来说太过分了,我想让它以这种方式工作以用于学习目的。

move.h

// This is the node of the list
#ifndef MOVE_H
#define MOVE_H

typedef struct s_move *MOVE;

/* Initializes a new move */
MOVE move_init(int i, int j);

#endif

move.c

#include <stdlib.h>
#include <stdio.h>

#include "move.h"

struct s_move {
    int i;
    int j;
    MOVE *next;
};

MOVE move_init(int i, int j) {
  MOVE m;
  m->i = i;
  m->j = j;
  m->next = NULL;
  return m;
}

moves.h

#ifndef MOVES_H
#define MOVES_H

#include "move.h"

typedef struct s_moves *MOVES;

/* Initializes the list of moves */
MOVES moves_init();

/* Appends a new move at the end of the list */
void moves_append(MOVES moves, MOVE move);

#endif

moves.c

#include <stdlib.h>

#include "moves.h"
#include "move.h"

struct s_moves {
  MOVE *head;
};

MOVES moves_init() {
  MOVES m;

  m->head = (MOVE *)malloc(sizeof(MOVE));
  m->head = NULL;
  return m;
}

void moves_append(MOVES moves, MOVE move) {
  MOVE *ptr;
  //***********************************
  //HERE I GET THE ERROR ON ptr->next
  //***********************************
  for(ptr = moves->head; ptr->next != NULL; ptr = ptr->next) {
    //do stuff
  }
}

执行此操作的正确方法是什么?抱歉,如果我重复自己的话,我想在不简化结构的情况下使用 ADT。谢谢!

您收到此错误的原因是变量ptrMOVE * 的类型,展开后变为struct s_move **。也就是说,变量 ptr 是指向类型 struct s_move 对象的指针,或者我们可以说变量 ptr 不存储任何结构或联合,而是存储一个指针。因此,您得到的错误。

我建议您将您编写的 typedef 替换为以下内容:

typedef struct s_move MOVE

typedef struct s_moves MOVES

虽然,我不知道这些结构将如何实际使用的细节,但用上面的结构替换你的 typedefs 应该可以解决错误。