Say I have

#include<iostream.h>

int tempNum;

struct node {
        int data;
        struct node *next;
};
struct node *newNode = NULL;

int main(void) {
        tempNum = 5;
        newNode->data = tempNum; //gives seg fault
}

*edit - I'm trying to add tempNum to the very first node.

I haven't worked with linked lists in a while and it's really giving me a headache. What's wrong?

A nice link for linked lists: click

a few things:
- Why is tempnum a global variable?
- iostream.h is outdated, use <iostream> instead.
- you probably want to post this is the C++ forum
- main always return something (an int)

The reason why the program crashes is this line:

struct node *newNode = NULL;

You make a pointer to a node struct and then point it to nothing (NULL). ==> Seg fault

Niek

I was going nuts when I wrote this, it's supposed to be #include<stdio.h>, very sorry.

*edit - So do I just need to allocate a memory location to newNode? If so how?

*edit - So do I just need to allocate a memory location to newNode? If so how?

Using malloc defined in stdlib.h

*newNode = malloc ( sizeof ( struct node ) );

Any dynamic memory you allocate, it needs to be freed at some point, when you're done; using the function free().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.