问题描述
我正在尝试在 C 中实现一个 List ADT,但我在互联网上找不到太多帮助,因为它似乎是 C++ 中的一个例子,我对此一无所知。我可以完全理解数据结构(至少,我想我已经理解了),但是我在将其设为 ADT、分离文件等方面遇到了麻烦。
尝试实现 append 函数时,在遍历列表的循环中,我收到如下错误:
member reference base type 'MOVE' (aka 'struct s_move *')is not a structure or union
我知道问题出在指针上,并通过稍微简化我的数据,因为这对于我正在解决的问题来说显然是过分的,我想让它以这种方式工作以用于学习目的。
移动.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。谢谢!
解决方法
您收到此错误的原因是变量ptr
的类型为 MOVE *
,展开后变为 struct s_move **
。也就是说,变量 ptr
是指向 struct s_move
类型对象的指针的指针,或者我们可以说变量 ptr
不存储任何结构或联合,而是存储一个指针。因此,您会遇到错误。
我建议您用以下内容替换您编写的 typedef:
typedef struct s_move MOVE
和
typedef struct s_moves MOVES
虽然,我不知道这些结构将如何实际使用的具体细节,但将您的 typedefs
替换为上述结构应该可以解决错误。