Problem with a pointer to struct type

0

My problem is this: I want to implement a TAD that allows me to go through a data collection of type string , entering values at the end and in the header .h I have the declaration:

typedef rep_string *coleccion;

In the .cpp file my rep_string is a struct with 3 fields: inicio (to restart the route), actual (to indicate the string pointed) and final (to add the data )

struct nodo {
char *frase
nodo *sig;
};

struct rep_string {
nodo *inicio;
nodo *actual;
nodo *final;
};

My question is whether the statement:

coleccion aux = new rep_string;

and later, when the collection has elements, the call:

aux->inicio->frase

are correct.

    
asked by Martín Larrosa Zugarramurdi 30.05.2018 в 19:23
source

2 answers

1
  

My question is whether the statement:

coleccion aux = new rep_string;
     

and later, when the collection has elements, the call:

aux->inicio->frase

They are. But those uses are not (in my opinion) adequate.

The alias hides the underlying type.

Normally when in C ++ we define a pointer type variable, we add the asterisk:

tipo_de_datos *puntero;
//            ~ <--- ¡Esto es un puntero!

But we can hide the pointer in an alias:

typedef tipo_de_datos * otro_tipo;
otro_tipo dato;
//        ~~~~ <--- Aunque sea puntero, ¡no lo sabemos de un vistazo!

In your case, due to this use of the alias, it is not evident that coleccion is a pointer and the code becomes confusing:

// Como? Guardamos el resultado de new en algo que NO PARECE UN PUNTERO?
coleccion aux = new rep_string;
// Un momento! Si aux no parece un puntero, por qué usa el operador flecha?
aux->inicio->frase

The use of an alias for a type should not detract from the code if it is not added.

Proposal.

Do not use aliases:

rep_string *aux = new rep_string;
// rellenar datos....
aux->inicio->frase

In the previous lines it is clear that aux is a pointer to rep_string , if you are too lazy to write twice rep_string you can use the automatic type deduction:

auto aux = new rep_string;
// rellenar datos....
aux->inicio->frase

We know that new always returns pointers, so looking at the definition of aux we see at once that it is a pointer.

    
answered by 31.05.2018 / 07:42
source
0
typedef struct 
{
    const char* frase;//value
    Node* next;//para apuntar al siguiente

}Node;

typedef struct 
{
    Node *inicio; 
    Node *actual;//aqui estariamos usando al nodo que nos hemos creado
    Node *final;
}Rep_String;


int main(int argc, char const *argv[])
{
    //la declaracion esta bien paraece, solo que no manejo bien por la forma que lo declaras
te recomendaria aprender un poco mas
    return 0;
}
    
answered by 31.05.2018 в 00:49