Structs Beispiel

Reading time ~1 minute


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

int main(int argc, char **argv)
{
    // basics
    struct person
    {
        int age;
        char name[100];
    };

    typedef struct person pers;
    typedef pers *pPers;

    struct person hansi;
    hansi.age = 35;
    strcpy(hansi.name, "HANSI HANSEN\n");
    printf("%i %s\n", hansi.age, hansi.name);

    pers dagmar;
    dagmar.age = 36;
    strcpy(dagmar.name, "DAGMAR DURR\n");
    printf("%i %s\n", dagmar.age, dagmar.name);

    pPers glug;
    glug = malloc(sizeof(pers));
    glug->age = 10;
    strcpy(glug->name, "GLUG GLUCK\n");
    printf("%i %s\n", glug->age, glug->name);


    // linked list
    typedef struct element
    {
        int val;
        struct element *next;
    } element_t;

    typedef element_t *pElement_t;

    pElement_t head = NULL;
    pElement_t elem = NULL;

    // list fill
    for(int i = 1; i <= 10; i++)
    {
        elem = malloc(sizeof(*elem));
        elem->val = i;
        elem->next  = head;
        head = elem;
    }

    // list print
    while (elem)
    {
        printf("%i\n", elem->val);
        elem = elem->next;
    }

    return 0;
}