How to access a structure within another structure

2

I have the following example code in which I try to insert a structure into another, but then I do not 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
#include <stdio.h>
#include <stdlib.h>

typedef struct Ejemplo{
    void* data;
} ejemplo;

typedef struct Dentro{
    char* dataDentro;
} dentro;

int main(){
    char nombre[] = "Cris%pre%";

    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;
}
"; 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 does not work and produces an error in the printf line

  

error: member reference base type 'void' is not a structure or         union

How should this be done to make it work?

    
asked by Cristofer Fuentes 20.03.2017 в 16:40
source

2 answers

2

Your problem is that you are de-referencing a pointer to void .

A priori you are accessing the sub-structure correctly, but there is no way to interpret what is the pointer data contained in Ejemplo . Since void is not a Dentro , the arrow operator ( -> ) will not be able to access dataDentro .

Solution.

Applies a type transformation:

ejemplo* estructura = malloc(sizeof(ejemplo));
dentro* estructuraInterior = malloc(sizeof(dentro));

estructuraInterior->dataDentro = nombre;
estructura->data = estructuraInterior;

printf("\n%s\n ", ((dentro *)estructura->data)->dataDentro);
//                 ^^^^^^^^^^
//                 Transforma el puntero a 'void' a puntero a 'dentro'.
    
answered by 20.03.2017 / 16:55
source
2

First, you do

typedef struct Ejemplo{
  void* data;
} ejemplo;

and then, you try to access data as if it were a dentro , which causes the error.

The simplest solution: predeclare struct Dentro :

struct Dentro;

typedef struct Ejemplo{
  struct Dentro* data;
} ejemplo;

typedef struct Dentro {
...
    
answered by 20.03.2017 в 16:53