I am currently trying to learn how linked lists as a personal project. I understand the core concepts and I have been trying to implement it into c. My program looks like it should work, keep in mind I am still new to programming :D
I created a structer pointer called head. head will point to the first node in the linked_list and startPtr will contain the address of head. Each time the function add is called a new node will be created and allocated some space in memory then the previously created node will point to the new node.
I know where my program is crashing but I can see why? It compiles fine.
My code crashes on the line
(*prevNode)->link = newNode;
This is the way I see this code: I pass the double pointer startPtr into the function add. I then created a new node using malloc. Next I deference startPtr ( which is called prevNode in the function ) which should contain the memory address of head....right? I then use the "->" expression to point the the structure pointer inside head called link.
The program just ends at this point and I have no idea why. I have looked at other linked list c codes but most of them don't use double pointers they just declare global structers and pointers. I am using GCC as my compiler.
Anyone know why this is happening?
#include <stdio.h>
#include <stdlib.h>
// STRUCTURES
struct node
{
int data;
struct node *link;
}*head;
void add( int, struct node ** );
int main()
{
struct node *head;
struct node **startPtr;
startPtr = head;
struct node *nodePtr;
int userInput;
int inputData;
do{
printf( "\n\n1: enter new node\n" );
printf( "2: Print Nodes\n" );
printf( "\n\nEnter: " );
scanf( "%d", &userInput );
if ( userInput == 1 )
{
printf( "\n\nEnter data:");
scanf("%d", &inputData );
add( inputData, startPtr );
}
}while( userInput == 1 );
// printing linked list
nodePtr = head->link;
while( nodePtr->link != NULL )
{
printf( "%d\n", nodePtr->data);
nodePtr = nodePtr->link;
}
printf( "%d\n", nodePtr->data);
return 0;
}// END main()
void add( int num, struct node **prevNode )
{
// assigning memory for a new node
struct node *newNode = malloc( sizeof( struct node ) );
(*prevNode)->link = newNode;
newNode->data = num;
newNode->link = NULL;
prevNode = &newNode;
}// END add()
Also I have one other question which I couldn't find and answer to online. when I create a pointer to a structer e.g. struct node *ptr;. does the structer pointer my default store the address of it's self. by its self I mean the structer, so if I print ptr will it output the address of the structer ptr?
startPtr = head
is btw not even valid C. Ok so this code won't even compile. We really needed to re-open this question, right...head
makes even less sense. This global variable is shadowed by a local variable.