Listy dynamiczne, błędna procedura dodaj

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

struct element
{
    char a[25];
    char b[25];
    struct element *next;
};

void dodaj(struct element *start, char *x, char *y)
{
    struct element *tmp = (struct element*)malloc(sizeof(struct element));



    strcpy(tmp->a, x);
    strcpy(tmp->b, y);

    if(start==NULL)
    {
       start=tmp;
       tmp->next=NULL;
    }
    else
    {
       tmp->next=start;
       start=tmp;
    }
}


int main()
{
    struct element *start, *pomoc;
    char x[25]="Amek", y[25]="lel";
    start=NULL;
    dodaj(start, x, y);

    printf("%s", start->a);

    return 0;
}
 

Problem polega na tym, że ta procedura DODAJ nie działa, nie umiem zrozumieć dlaczego.
Wypisuje mi ze start=NULL. Nie umiem znaleźć błędu. Ktoś może pomóc?

3

Na szybko...
Powinno być tak:

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

struct element
{
    char a[25];
    char b[25];
    struct element *next;
};

void dodaj(struct element **start, char *x, char *y)
{
    struct element *tmp = (struct element*)malloc(sizeof(struct element));
    strcpy(tmp->a, x);
    strcpy(tmp->b, y);

    if(start==NULL)
    {
       (*start)=tmp;
       tmp->next=NULL;
    }
    else
    {
       tmp->next=(*start);
       (*start)=tmp;
    }
}

void wypisz(struct element *glowa){
    struct element *temp = glowa;
    if(temp){
        while(temp){
            printf("%s, %s\n", temp->a, temp->b);
            temp = temp->next;
        }
    }
}


int main()
{
    struct element *start;
    char x[25]="Amek", y[25]="lel";
    char w[25]="COOL", z[25]="hej";
    start=NULL;
    dodaj(&start, x, y);
    dodaj(&start, w, z);
    wypisz(start);
    return 0;
}

Przekazywałeś tylko kopie wskaźnika i dlatego nie wypisywało tego co trzeba.
Poza tym nie było funkcji wypisywania zawartości listy.

Dodatkowo dorób jeszcze niszczenie elementów, bo będziesz miał wycieki pamięci.

3

zapraszam do lektury: Przekazywanie parametru przez wartość i referencję

jeśli jednak nadal będziesz miał pytania to pisz śmiało.

0

Dzięki wielkie, za chwilę sobie poczytam. Jesteście super.

1 użytkowników online, w tym zalogowanych: 0, gości: 1