errore di compilazione: richiesta di membro in qualcosa che non è una struttura o un'unione
-
29-10-2019 - |
Domanda
Modifica: Il codice qui sotto è stato modificato per funzionare in quanto è stato risolto il problema.
In particolare, (*hardwareList.next_item)->next
è stato scritto originariamente senza staffe (ad esempio *hardwareList.next_item->next
) e il compilatore non lo capiva.
Sto cercando di allenarti perché il compilatore si sta confondendo con il mio codice C.Sto cercando di creare un elenco collegato che memorizza tutti gli articoli e anche un puntatore all'indirizzo dell'ultima variabile "Avanti", per un facile aggiunta.
.
typedef struct {
int recordNum;
char toolName[25];
int quantity;
float cost;
} HardwareData;
typedef struct _HardwareListItem{
HardwareData data;
struct _HardwareListItem* next;
} HardwareListItem;
typedef struct _HardwareList {
HardwareListItem* items;
HardwareListItem** next_item;
} HardwareList;
HardwareList readFromFile(FILE* fp)
{
char stopReading = 0;
HardwareList hardwareList = {0};
hardwareList.next_item = &hardwareList.items;
do {
*hardwareList.next_item = (HardwareListItem*)calloc(1, sizeof(HardwareData));
if (*hardwareList.next_item == NULL)
{
fprintf(stderr, "OOM Reading File\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
if (fread(&((*hardwareList.next_item)->data), sizeof(HardwareData), 1, fp) != 1) {
free(*hardwareList.next_item);
*hardwareList.next_item = NULL;
stopReading = 1;
} else {
hardwareList.next_item = &((*hardwareList.next_item)->next);
}
} while(!stopReading);
return hardwareList;
}
Compiler dice:
.line 31: error: request for member 'data' in something not a structure or union
line 36: error: request for member 'next' in something not a structure or union
Soluzione
Immagino che il problema sia questo pezzo di codice: *(hardwareList.next_item)->data
next_item
è un puntatore a un puntatore, quindi la mia ipotesi è che il compilatore lo legga come *((hardwareList.next_item)->data)
che ovviamente non funziona - i puntatori non hanno membri in C.
Prova ((*(hardwareList.next_item))->data)
per ottenere l'ordine di dereferenziazione corretto.
Altri suggerimenti
hardwareList.next_item
è HardwareListItem**
, quindi operatore ->
su di esso restituisce HardwareListItem*
, che ovviamente non è una struttura.
Stai usando troppi puntatori, è confuso.Prova a semplificare il tuo codice, hai tonnellate di bug lì.