Why is this linked list not working?

Started by
7 comments, last by thyrgle 13 years, 1 month ago
I am trying to build a simple to chain linked with the following code:

struct node {
int data;
struct node* next;
};

int main (int argc, char * const argv[]) {
struct node *start_ptr = NULL;
struct node *newpointer = NULL;
newpointer->next = NULL;
start_ptr->next = newpointer;
return 0;
}


But, when I run I get EXC_BAD_ACCESS at newpointer->next = NULL; and do not know why. Any help on the matter would be appreciated.
Advertisement
newpointer is NULL.. so you're trying to dereference a NULL pointer. You need to allocate memory for the node, for example with new or malloc. Is this supposed to be C or C++?
Ok, well I actually got it to work by changing it to the following:

struct node {
int data;
struct node* next;
};

int main (int argc, char * const argv[]) {
node *start_ptr = new node;
node *newpointer = new node;
newpointer->next = NULL;
start_ptr->next = newpointer;
return 0;
}


But, I am confused on why the new node is need and and why I can't just use NULL?

newpointer is NULL.. so you're trying to dereference a NULL pointer. You need to allocate memory for the node, for example with new or malloc. Is this supposed to be C or C++?


It is C++.
Moving to For Beginners.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]


Ok, well I actually got it to work by changing it to the following:

struct node {
int data;
struct node* next;
};

int main (int argc, char * const argv[]) {
node *start_ptr = new node;
node *newpointer = new node;
newpointer->next = NULL;
start_ptr->next = newpointer;
return 0;
}


But, I am confused on why the new node is need and and why I can't just use NULL?

If you don't allocate memory for your pointer to point to, then there is no next-member anywhere that you can access. NULL is not a pointer to a valid node object, which is why it cannot be used.

But, I am confused on why the new node is need and and why I can't just use NULL?


newpointer is a POINTER to a node object
To access the members of the node object that newpointer is pointing to you use ->

If newpointer is set to NULL then it is not pointing to any valid node object. How can you access the members of an object when it isn't pointing to one?
Well, how can NULL have a next field?
NULL indicates the end of a linked list. There is no life after NULL.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Ok, I get it now, making a struct node* does not make an actual node so I have to make one that goes along with it. Thanks for everyone's help!

This topic is closed to new replies.

Advertisement