Witam, muszę ogarnąć temat struktur i dynamicznego alokowania pamięci. O ile samo w sobie nie jest to dla mnie truden to nie bardzo mogę sobie wyobrazić istoty dynamicznego alokowania pamięci. Jako najprostszy przykład wybrałem dodawanie elementu do listy jednokierunkowej. Przykład z dynamicznym alokowaniem pamięci:
#include <stdio.h>
#include <stdlib.h>
struct Unit {
int number;
struct Unit *child;
};
void add(struct Unit *);
int main(void) {
struct Unit main = {0};
add(&main);
printf("%d", main.child->number);
return 0;
}
void add(struct Unit *parent) {
struct Unit *start = parent;
while (start->child) {
start = start->child;
}
struct Unit *child = (struct Unit *) malloc(sizeof(struct Unit));
child->number = 55;
start->child = child;
}
Wszystko działa fajnie, a teraz funkcja "tradycyjna":
void add(struct Unit *parent) {
struct Unit *start = parent;
while (start->child) {
start = start->child;
}
struct Unit child;
child.number = 55;
start->child = &child;
}
W obu przypadkach wynik taki sam. Po co (choćby w przypadku listy jednokierunkowej) używać dynamicznego alokowania pamięci? Co nam to w istocie daje, oprócz tego, że potem w mainie mogę sobie zwolnić tę pamięć? Chicłabym usłyszeć od kogoś praktyczną tego stronę. Dzięki!