[C con Clase] duda apuntadores
omar mendoza
omar.p9 en gmail.com
Dom Ene 4 07:00:57 CET 2015
¡Hola a todos!
Tengo una duda sobre apuntadores, si tengo
struct Punto_ {
float x;
float y;
};
typedef struct Punto_ Punto;
void suma(Punto *p, Punto *p1, Punto *p2) {
p->x = p1->x + p2->x;
p->y = p1->y + p2->y;
}
void show(Punto *p) {
printf("(x,y) = (%.2f, %.2f)\n", p->x, p->y);
}
int main()
{
printf("Iniciando...\n");
Punto *p = (Punto *) malloc(sizeof(Punto));
Punto *pp = (Punto *) malloc(sizeof(Punto));
Punto *p_ = (Punto *) malloc (sizeof(Punto)); // diferencia
if (p == NULL || pp == NULL || p_ == NULL) {
fprintf(stderr, "Memoria no suficiente");
return 0;
}
p->x = 1.;
p->y = 2.;
pp->x = 1.;
pp->y = 2.;
show(p);
show(pp);
suma(p_, p, pp); // diferencia
show(p_); // diferencia
free(p);
free(pp);
free(p_);
return 0;
}
Cuál sería la diferencia si hago
int main()
{
printf("Iniciando...\n");
Punto *p = (Punto *) malloc(sizeof(Punto));
Punto *pp = (Punto *) malloc(sizeof(Punto));
Punto p_; // diferencia
if (p == NULL || pp == NULL) {
fprintf(stderr, "Memoria no suficiente");
return 0;
}
p->x = 1.;
p->y = 2.;
pp->x = 1.;
pp->y = 2.;
show(p);
show(pp);
suma(&p_, p, pp); // diferencia
show(&p_); // diferencia
free(p);
free(pp);
return 0;
}
/////
Es decir entre crear en el main
Punto *p_ = (Punto *) malloc ....
Punto p_;
y pasarlo a las funciones
suma(p_, p, pp)
suma(&p_, p. pp)
show(p_);
show(&p_);
Espero me haya explicado...
Saludos
--
Omar Jonathan Mendoza Bernal
"Las cicatrices nos recuerdan que el pasado fue real" Dr. Lecter en Dragón
Rojo
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://listas.conclase.net/pipermail/cconclase_listas.conclase.net/attachments/20150104/b54a3740/attachment.html>
Más información sobre la lista de distribución Cconclase