sexta-feira, 1 de junho de 2012

Usando typedef, struct, malloc e free


A seguir temos alguns exemplos de fácil compreensão.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    int id;
    char name[30];
} elemento;

typedef struct node{
    struct node *next;      // forma correta
    // node *previous;      // declaração errada
    elemento *dados;
} node;

typedef struct tag{
    int key;
    int value;
} tag;

int main()
{
    elemento *prod = (elemento *) malloc( sizeof( elemento ));

    prod->id = 123;
    strcpy( prod->name, "teste");

    node *n = (node *) malloc( sizeof(node));

    n->next = NULL;
    n->dados = prod;

    free( n->dados );
    free( n );

    tag *a = (tag *) malloc( sizeof( tag ));

    a->key = 12;
    a->value = 14;

    free( a );

    struct tag *b = (struct tag *) malloc( sizeof( struct tag ));

    b->key = 120;
    b->value = 140;

    free( b );

    struct point3d {
        int x;
        int y;
        int z;
    };

    struct point3d *ptr = (struct point3d *) malloc( sizeof( struct point3d ));

    ptr->x = 10;
    ptr->y = 20;
    ptr->z = 30;

    free( ptr );

    typedef struct point{
        int x;
        int y;
    } point;

    point *q = (point *) malloc( sizeof( point ));

    q->x = 39;
    q->y = 67;

    free( q );

    return 0;
}




Link relacionado ao assunto:

RE: typedef struct vs struct
http://www.netalive.org/codersguild/posts/1753.shtml

Um comentário:

Gustavo Adolfo disse...

Tenho aprendido mais sobre C nas aulas de lógica que nas de C propriamente. Obrigado.