I am trying to implement a List ADT in C, but I couldn't find much help on the intenet since it seems like very example is in C++ which I don't know anything about. I can completely understand the data stucture (at least, I think I understood) but I have trouble making it an ADT, separating files and so on.
When trying to implement the append function, in the cycle that traverses the list I get an error like:
member reference base type 'MOVE' (aka 'struct s_move *')is not a structure or union
I understand that the problem is with pointers and by simplifying a bit my data, since this is clearly ovekill for the problem I'm solving, I'd like to make it work this way for learning purposes.
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
}
}
Which is the right way to do this? Sorry if I'm repeating myself, I'd like to use ADT without simplifying the structure. Thanks!
The reason you are getting this error is that the variableptr
is of the type of MOVE *
which when expanded becomes struct s_move **
. That is, the variable ptr
is a pointer to a pointer to an object of type struct s_move
or we can say that the variable ptr
doesn't store any structure or union and instead it stores a pointer. Hence, the error you are getting.
What I suggest you do is replace the typedefs you have written with the following :
typedef struct s_move MOVE
and
typedef struct s_moves MOVES
Although, I don't know the specifics about how theses structures will actually be used but replacing your typedefs
with the above ones should resolve the errors.