I have the following sample code in which I try to insert a structure inside another, but then I don't know how to access its fields.
#include <stdio.h>
#include <stdlib.h>
typedef struct Ejemplo{
void* data;
} ejemplo;
typedef struct Dentro{
char* dataDentro;
} dentro;
int main(){
char nombre[] = "Cris\0";
ejemplo* estructura = malloc(sizeof(ejemplo));
dentro* estructuraInterior = malloc(sizeof(dentro));
estructuraInterior->dataDentro = nombre;
estructura->data = estructuraInterior;
printf("\n%s\n ", estructura->data->dataDentro);
return 0;
}
This doesn't work and produces an error on the printf line
error: member reference base type 'void' is not a structure or union
How should this be done for it to work?
First, you do
and then you try to access
data
as if it were adentro
, which causes the error.The simplest solution: predeclare
struct Dentro
:Your problem is that you are dereferencing a pointer to
void
.A priori you are correctly accessing the sub-structure, but there is no way to interpret what is the pointer
data
contained inEjemplo
. Sincevoid
is not aDentro
, the arrow operator (->
) will not be able to accessdataDentro
.Solution.
Apply a type transformation: