Hello everyone,
I've just started reading "Crafting Interpreters" by Robert Nystrom, where there's an exercise right at the beginning about writing a doubly linked list of strings in C to get some practice with pointers. Maybe this forum is not meant for such specific questions, in which case I'm sorry!
I'm using Apple LLVM version 10.0.0 (clang-1000.11.45.5) in case it's relevant, but I think my mistake is more of a misunderstanding or logic error of some sort.
I've just started, and I'm trying to get the logic right, before I allocate and free the strings like stated in the exercise.
My first approach is working:
Code:
#include <stdio.h>
typedef struct List List;
typedef struct Element Element;
struct Element {
char* str;
Element* next;
Element* prev;
};
struct List {
Element* first;
Element* last;
};
void add(List* l, char* str) {
Element e = {str, NULL, NULL};
if (l->first == NULL) {
l->first = &e;
l->last = &e;
}
}
void printelements(List* l) {
Element* e;
for (e = l->first; e != NULL; e = e->next) {
printf("%s\n", e->str);
}
}
int main() {
List l = {NULL, NULL};
char* a = "this is the first element";
char* b = "second element :)";
add(&l, a);
printelements(&l);
return 0;
}
But when I'm trying to do the same with e being a pointer, I've got the output:
"this is the first element
Segmentation fault: 11"
With only the following differences:
Code:
void add(List* l, char* str) {
Element *e = &(Element){str, NULL, NULL};
if (l->first == NULL) {
l->first = e;
l->last = e;
}
}
I would be very grateful for any advice on what I am doing wrong at this point.
Thank you very much!
Best regards,
smh1