DaemonForums  

Go Back   DaemonForums > Miscellaneous > Programming

Programming C, bash, Python, Perl, PHP, Java, you name it.

Reply
 
Thread Tools Display Modes
  #1   (View Single Post)  
Old 1 Week Ago
smh1 smh1 is offline
New User
 
Join Date: Sep 2021
Posts: 9
Default Specific (newbie) question to Pointers in C

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
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Specific WiFi NIC Support marcolino FreeBSD General 3 14th April 2023 05:07 PM
block specific Lan IP from internet bsdsource OpenBSD Security 2 5th June 2017 02:20 PM
Newbie kernel question sbonar Programming 11 17th August 2009 11:40 PM
Jails, ezjail, apache, very newbie question. neurosis FreeBSD General 15 23rd August 2008 01:38 PM
Newbie question about ajunta install Johnny2Bad Programming 3 8th June 2008 05:57 PM


All times are GMT. The time now is 05:18 PM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Content copyright © 2007-2010, the authors
Daemon image copyright ©1988, Marshall Kirk McKusick