Test Foro de elhacker.net SMF 2.1

Programación => Programación C/C++ => Mensaje iniciado por: Omar_2013 en 2 Septiembre 2013, 18:56 PM

Título: Problema Con Un Arreglo Dinamico De Estructuras [?]
Publicado por: Omar_2013 en 2 Septiembre 2013, 18:56 PM
#include <cstdlib>
#include <iostream>


using namespace std;

struct Datos {
      char *Nombre;
      int Edad;
};

struct Categorias {
      char *Deporte;
      int Atletas;
      Datos *Informacion;
};

int main(int argc, char *argv[])
{  
   Categorias *Otro= new Categorias[10];
   
   Otro[0].Informacion->Nombre="Oscar";
       
   system("PAUSE");
   return EXIT_SUCCESS;
}


Pordrian por favor ayudarme .. el codigo compila pero el ejecutable se totea
Título: Re: Problema Con Un Arreglo Dinamico De Estructuras [?]
Publicado por: amchacon en 2 Septiembre 2013, 19:14 PM
En la estructura, Información es un puntero y no un objeto. Si no inicializas el puntero te va a dar error.

Solución 1, convertirlo de puntero a objeto:

Código (cpp) [Seleccionar]
#include <cstdlib>
#include <iostream>

using namespace std;

struct Datos {
       char *Nombre;
       int Edad;
};

struct Categorias {
       char *Deporte;
       int Atletas;
       Datos Informacion;
};

int main(int argc, char *argv[])
{
    Categorias *Otro= new Categorias[10];

    Otro[0].Informacion.Nombre = "Miau";

    return EXIT_SUCCESS;
}


Solución 2:

Código (cpp) [Seleccionar]
#include <cstdlib>
#include <iostream>

using namespace std;

struct Datos {
       char *Nombre;
       int Edad;
};

struct Categorias {
       char *Deporte;
       int Atletas;
       Datos *Informacion;
};

int main(int argc, char *argv[])
{
    Categorias *Otro= new Categorias[10];

    Otro[0].Informacion = new Datos;

    Otro[0].Informacion->Nombre= "Oscar";

    return EXIT_SUCCESS;
}


Solución 3, usar un constructor que lo inicialize:

Código (cpp) [Seleccionar]
#include <cstdlib>
#include <iostream>

using namespace std;

struct Datos {
       char *Nombre;
       int Edad;
};

struct Categorias {
       char *Deporte;
       int Atletas;
       Datos *Informacion;

       Categorias() { Informacion = new Datos;}
};

int main(int argc, char *argv[])
{
    Categorias *Otro= new Categorias[10];

    Otro[0].Informacion->Nombre= "Oscar";

    return EXIT_SUCCESS;
}


Solución 4, inicializar nombre desde un constructor:

Código (cpp) [Seleccionar]
#include <cstdlib>
#include <iostream>

using namespace std;

struct Datos {
       char *Nombre;
       int Edad;

       Datos(char* nombre) : Nombre(nombre) {}
};

struct Categorias {
       char *Deporte;
       int Atletas;
       Datos *Informacion;

       Categorias(char* Nombre = NULL) { Informacion = new Datos(Nombre);}
};

int main(int argc, char *argv[])
{
    Categorias *Otro= new Categorias("Oscar");

    return EXIT_SUCCESS;
}

Título: Re: Problema Con Un Arreglo Dinamico De Estructuras [?]
Publicado por: Omar_2013 en 2 Septiembre 2013, 19:21 PM
Gracias.