I am trying to insert into linked list but I am not getting proper output when display() method is called. Everything is fine while inserting data into the linked list.
The printf statement in insert() method prints :
a int
b int
c int
But when display() method is called it prints :
c
c
c
Datatype member of the structure doesn't get printed at all. And, I think identifierName member gets overwrite every time. Following I snippet of my code :
struct symbol
{
char* identifierName;
char* datatype;
struct symbol* next;
};
void insert(struct symbol** headRef,char* identifier,char* type)
{
struct symbol* newnode = (struct symbol*) malloc(sizeof(struct symbol));
newnode->identifierName = identifier;
newnode->datatype = type;
newnode->next = (*headRef);
(*headRef) = newnode;
printf("%s %s\n",newnode->identifierName,newnode->datatype); //debugging
}
void display(struct symbol* node)
{
while(node!=NULL)
{
printf("%s %s\n",node->identifierName,node->datatype);
node = node->next;
}
}
It seems that you need to make copies of the strings passed as arguments of the function.
Change the function the follwoing way
#include <string.h>
//...
void insert(struct symbol** headRef,char* identifier,char* type)
{
struct symbol* newnode = (struct symbol*) malloc(sizeof(struct symbol));
if ( newnode )
{
newnode->identifierName = malloc( strlen( identifier ) + 1 );
strcpy( newnode->identifierName, identifier );
newnode->datatype = malloc( strlen( type ) + 1 );
strcpy( newnode->datatype, type );
newnode->next = *headRef;
*headRef = newnode;
printf("%s %s\n",newnode->identifierName,newnode->datatype); //debugging
}
}
Take into account that the function expects that paramameters identifier and type are pojnters to first characters of strings.
If for example parameter identifier is a pointer to a single character then instead of
newnode->identifierName = malloc( strlen( identifier ) + 1 );
strcpy( newnode->identifierName, identifier );
you have to write
newnode->identifierName = malloc( sizeof( char ) );
*newnode->identifierName = *identifier;
Also do not forget to free memory pointed to by these pointers when a node is deleted.
replace these two lines
newnode->next = (*headRef);
(*headRef) = newnode;
with
newnode->next = headRef->next;
headRef = newnode;
Related
I'm currently learning C and also some datastructures such as binary search trees etc. I have trouble understanding HOW exactly changing pointer values within a function works in some cases and in others doesn't... I'll attach some of my code I wrote. It's an insert function which inserts values in the correct places in the BST (it works as it should). I tried working with pointers to pointers to be able to change values withing a function. Even though it works, im still really confused why it actually does.
I don't quite understand why my insert function actually changes the BST even though I only work with local variables (tmp, parent_ptr) in my insert function and I don't really dereference any pointers apart from " tmp = *p2r " in the insert function.
Thanks for helping out.
#include <stdio.h>
#include <stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode** createTree(){
struct TreeNode** p2r;
p2r = malloc(sizeof(struct TreeNode*));
*p2r = NULL;
return p2r;
}
void insert(struct TreeNode** p2r, int val){
// create TreeNode which we will insert
struct TreeNode* new_node = malloc(sizeof(struct TreeNode));
new_node -> val = val;
new_node -> left = NULL;
new_node -> right = NULL;
//define onestep delayed pointer
struct TreeNode* parent_ptr = NULL;
struct TreeNode* tmp = NULL;
tmp = *p2r;
// find right place to insert node
while (tmp != NULL){
parent_ptr = tmp;
if (tmp -> val < val) tmp = tmp->right;
else tmp = tmp->left;
}
if (parent_ptr == NULL){
*p2r = new_node;
}
else if (parent_ptr->val < val){ //then insert on the right
parent_ptr -> right = new_node;
}else{
parent_ptr -> left = new_node;
}
}
int main(){
struct TreeNode **p2r = createTree();
insert(p2r, 4);
insert(p2r, 2);
insert(p2r, 3);
return 0;
}
Let's analyze the approach step by step.
At first we consider the following simple program.
#include <stdio.h>
#include <stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void create( struct TreeNode *head, int val )
{
head = malloc( sizeof( struct TreeNode ) );
head->val = val;
head->left = NULL;
head->right = NULL;
}
int main(void)
{
struct TreeNode *head = NULL;
printf( "Before calling the function create head == NULL is %s\n",
head == NULL ? "true" : "false" );
create( head, 10 );
printf( "After calling the function create head == NULL is %s\n",
head == NULL ? "true" : "false" );
return 0;
}
The program output is
Before calling the function create head == NULL is true
After calling the function create head == NULL is true
As you can see the pointer head in main was not changed. The reason is that the function deals with a copy of the value of the original pointer head. So changing the copy does not influence on the original pointer.
If you rename the function parameter to head_parm (to distinguish the original pointer named head and the function parameter) then you can imagine the function definition and its call the following way
create( head, 10 );
//...
void create( /*struct TreeNode *head_parm, int val */ )
{
struct TreNode *head_parm = head;
int val = 10;
head_parm = malloc( sizeof( struct TreeNode ) );
//...
That is within the function there is created a local variable head_parm that is initialized by the value of the argument head and this function local variable head_parm is changed within the function.
It means that function arguments are passed by value.
To change the original pointer head declared in main you need to pass it by reference.
In C the mechanism of passing by reference is implemented by passing an object indirectly through a pointer to it. Thus dereferencing the pointer in a function you will get a direct access to the original object.
So let's rewrite the above program the following way.
#include <stdio.h>
#include <stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void create( struct TreeNode **head, int val )
{
*head = malloc( sizeof( struct TreeNode ) );
( *head )->val = val;
( *head )->left = NULL;
( *head )->right = NULL;
}
int main(void)
{
struct TreeNode *head = NULL;
printf( "Before calling the function create head == NULL is %s\n",
head == NULL ? "true" : "false" );
create( &head, 10 );
printf( "After calling the function create head == NULL is %s\n",
head == NULL ? "true" : "false" );
return 0;
}
Now the program output is
Before calling the function create head == NULL is true
After calling the function create head == NULL is false
In your program in the question you did not declare the pointer to the head node like in the program above
struct TreeNode *head = NULL;
You allocated this pointer dynamically. In fact what you are doing in your program is the following
#include <stdio.h>
#include <stdlib.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void create( struct TreeNode **head, int val )
{
*head = malloc( sizeof( struct TreeNode ) );
( *head )->val = val;
( *head )->left = NULL;
( *head )->right = NULL;
}
int main(void)
{
struct TreeNode **p2r = malloc( sizeof( struct TreeNode * ) );
*p2r = NULL;
printf( "Before calling the function create *p2r == NULL is %s\n",
*p2r == NULL ? "true" : "false" );
create( p2r, 10 );
printf( "After calling the function create *p2r == NULL is %s\n",
*p2r == NULL ? "true" : "false" );
return 0;
}
The program output is
Before calling the function create *p2r == NULL is true
After calling the function create *p2r == NULL is false
That is compared with the previous program when you used the expression &head of the type struct TreeNode ** to call the function create you are now introduced an intermediate variable p2r which stores the value of the expression &head due to this code snippet
struct TreeNode **p2r = malloc( sizeof( struct TreeNode * ) );
*p2r = NULL;
That is early you called the function create like
create( &head, 10 );
Now in fact you are calling the function like
struct TreeNode **p2r = &head; // where head was allocated dynamically
create( p2r, 10 );
The same takes place in your program. That is within the function insert dereferencing the pointer p2r you have a direct access to the pointer to the head node
if (parent_ptr == NULL){
*p2r = new_node;
^^^^
}
As a result the function changes the pointer to the head node passed by reference through the pointer p2r.
The data members left and right of other nodes are also changed through references to them using the pointer parent_ptr
else if (parent_ptr->val < val){ //then insert on the right
parent_ptr -> right = new_node;
^^^^^^^^^^^^^^^^^^^
}else{
parent_ptr -> left = new_node;
^^^^^^^^^^^^^^^^^^
}
While the pointers themselves are indeed local variables, they point to a specific location in memory. When you dereference the pointer by using the -> symbol, you're basically accessing the memory where that exact variable to which the pointer is pointing to is stored. This is why your changes are reflected outside the function as well.
You basically told a local variable where your tree is stored, it helped with the insertion, and then it went out of scope. The tree itself is not a local variable so the changes are reflected on it.
I suggest reading up on how pointers work.
First of all, always remember one thing about the pointers, they store a memory address, rather than a value. For example:
int val = 5;
int copy = val;
int *original = &val;
printf("%d\n", val);
printf("%d\n", copy);
printf("%d\n", *original);
val = 8;
printf("%d\n", val);
printf("%d\n", copy);
printf("%d\n", *original);
On executing this piece of code, the output will be
5
5
5
8
5
8
Notice, how on changing the value of val, the value of copy remains the same, and the value pointed the by original changes. This happens because the pointer original points to the memory location val.
Now, coming to the insert function, although you are only working with local variables(tmp, parent_ptr), but remember they are pointer variables, they refer to a memory address. So whenever within the loop, you traverse to tmp -> right or tmp -> left, you are actually jumping in memory from one location to another, in the correct order, that's why it works. The following example will make it more clear.
56 (A)
/ \
/ \
45 (B) 60 (C)
Consider the above BST, with the memory address in brackets. Let's insert 40 into this BST. Initially, tmp will point to A, address of 56. Now 40 is less than 56, so tmp goes to left and now points to B, address of 45. Once, again it goes to left and now it is null. But by now, parent_ptr points to B. So the new node for 40 gets attached to left of B.
56 (A)
/ \
/ \
45 (B) 60 (C)
/
/
40 (D)
I have a problem with linked lists in C. I made a function that created a new node of the list with some information (char *description) and added it to its end. The code is following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
char *description;
struct node *next;
};
// The function to create a node and append it to the linked list of nodes
struct node* create_node(struct node *first, char *description) {
struct node *current = first;
// Iteration through the list until the end
while(current != NULL) {
node++;
current = current -> next;
}
// Now pointer current points at the end of the list, first -> next. How to assign the pointer new to first -> next through current?
struct node *new = malloc(sizeof(struct container));
new -> next = NULL;
new -> description = malloc(sizeof(description));
memcpy(new -> description, description, sizeof(description));
current = new;
return current;
}
int main() {
// Creating the first node
struct node *first = create_node(NULL, "First");
// Creating and appending the second node to the list
create_node(first, "Second");
printf("%d\n", first -> next == NULL); // Prints 1, the newly created node hasn't been appended
return 0;
}
I searched how to create the list of the kind and saw very similar ways of how to do it. I know that it's something basic and most likely there's a simple solution, but I can't find it.
Thanks everyone for respond.
For starters the function name create_node is confusing. It is much better to name the function at least like append_node.
The second function parameter should have the qualifier const because the passed string is not changed in the function.
In these statements
new -> description = malloc(sizeof(description));
memcpy(new -> description, description, sizeof(description));
you are allocating memory of the size equal either to 8 or to 4 bytes depending on the value of sizeof( char * ) and correspondingly coping this number of bytes.
You have at least to write
new -> description = malloc( strlen(description));
memcpy(new -> description, description, strlen(description));
But it would be better if you were copying the whole string.
The function has a bug. It does not append a node to the list because within the function there is changed the local pointer current that is not chained to the list.
Take into account that memory allocation can fail. You should process such a situation.
The function can be safer and simpler if to pass the pointer to the head node by reference.
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char *description;
struct node *next;
};
// The function to create a node and append it to the linked list of nodes
int append_node( struct node **head, const char *description )
{
struct node *new_node = malloc( sizeof( struct node ) );
int success = new_node != NULL;
if ( success )
{
new_node->description = malloc( strlen( description ) + 1 );
success = new_node->description != NULL;
if ( success )
{
strcpy( new_node->description, description );
new_node->next = NULL;
while ( *head != NULL )
{
head = &( *head )->next;
}
*head = new_node;
}
else
{
free( new_node );
}
}
return success;
}
int main( void )
{
// Creating the first node
struct node *head = NULL;
if ( append_node( &head, "first" ) )
{
printf( "%s\n", head->description );
}
return 0;
}
The program output is
first
Hi I am new at this community. Lets try to help.
I thik you are pointing to the last node of the list and changing it to the new one at line
current = new;
But to link the new node you should save it in the field next of the node, try:
current->next=new;
I hope help you, bye :).
I'm trying to create a linked list holding char type data.
For some reason, the code does not work. The GCC compiler's warning for function "add_bottom_ListEl" is
"warning: passing argument 2 of 'add_bottom_listEl' makes integer from pointer without a cast"
and
"note: expected 'char' but argument is of type 'char * "
I suspect that there's something wrong about the way I use pointers, but I've tried many, many combinations, passing pointers to the function etc... But nothing seemed to work.
Here's main function and all the others used. MAX_CHAR is defined in all files (#define MAX_CHAR 30)
int main()
{
char name[MAX_CHAR];
scanf("%s", name);
ListEl *head = malloc(sizeof(ListEl));
strcpy(head->name, name);
head->next = NULL;
printf("%s", head->name);
add_bottom_listEl(head, name);
print_listEl(head);
return 0;
}
void add_bottom_listEl (ListEl *head, char name)
{
ListEl *newEl;
while(head->next!=NULL)
{
head=head->next;
}
newEl = (ListEl*) malloc(sizeof(ListEl));
strcpy(newEl->name, name);
newEl->next = NULL;
}
void print_listEl(ListEl* head)
{
puts("print");
ListEl* current = head;
while (current!=NULL)
{
int i=1;
printf("%d.%s\n", i, current->name);
++i;
current = current -> next;
}
}
The ListEl structure is just a regular element of a linked list
struct ListEl
{
char name[MAX_CHAR];
struct ListEl* next;
};
Obviously, I used
typedef struct ListEl ListEl;
Every linked list tutorial on the internet or this site is only showing how to handle lists with integers or numbers in general, but not arrays (chars). Can anyone help me out here?
Your function "add_bottom_listEl" takes one character called "name", not a character array (or a pointer to a character). My guess is you want it to be:
add_bottom_listEl(ListEl *head, char *name)
If your intention in add_bottom_listEl is to modify and pass back head, then head has to be passed as a pointer to a pointer:
void add_bottom_listEl(ListEl** head, char* name) {
if ( head == NULL ) {
//head is invalid, do nothing
return;
}
//Use calloc instead of malloc to initialise the memory area
ListEl* newEl = (ListEl*)calloc(1, sizeof(ListEl));
//Ensure only name of the permissible length is copied
strncpy(newEl->name, name, MAX_CHAR-1);
//No need to do this now...calloc will initialise it to NULL
//newEl->next = NULL;
if ( *head == NULL ) {
//No nodes in list yet, this is the first
*head = newEl;
} else if ( *head != NULL ) {
//Find the end of the list
while((*head)->next!=NULL) {
*head = (*head)->next;
}
}
//Add the new node to the list
*head = newel;
}
When you call this modified version of the function pass the address of the pointer:
add_bottom_listEl(&head, name);
You can make your typedef more readable by doing this:
typedef struct _listEl {
char name[MAX_CHAR];
struct _listEl* next;
} ListEl;
The line
void add_bottom_listEl (ListEl *head, char name)
should be
void add_bottom_listEl (ListEl *head, char* name)
This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 years ago.
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?
A lot to unpack here... these are uninitialized and then you alias a pointer rather than point to an address so you really don't have a pointer to a pointer you have 2 of the same pointer
struct node *head;
struct node **startPtr;
startPtr = head;
struct node *nodePtr;
maybe something like this:
struct node *head = NULL;
struct node **startPtr = &head;
struct node *nodePtr = NULL;
would be a better start... then in C you can't deref a NULL pointer so you have to check first if there is a possibility of a null pointer... note this wont check for uninitialized garbage values, which local variable can be:
if(startPtr && *startPtr)
{
// now you know you can deref startPtr twice,
// once to a pointer to an object (which might be null)
// then after then && you can deref to an actual object
}
Apart from this typo
startPtr = head;
^^^^
where has to be
startPtr = &head;
^^^^^
there are several problems with the code.
The first one is that the header was not initialized initially. So dereferencing this pointer results in undefined behavior.
The second problem is that this loop
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 );
is built logically incorrectly. For example if the user enters some number that is not equal to 1 or 2 then the program will try to output the list after exiting the loop.
The third one is as initially the header can be equal to null. So this statement in the function
(*prevNode)->link = newNode;
again invokes undefined behavior and moreover if *prevNode is not equal to NULL then all early appended nodes will be lost because its reference link is overwritten.
The function can look the following way
int add( struct node **head, int data )
{
struct node *newNode = malloc( sizeof( struct node ) );
int success = newNode != NULL;
if ( success )
{
newNode->data = data;
newNode->link = *head;
*head = newNode;
}
return success;
}
struct node *head;
never initialized
startPtr = head;
initialized to uninitialized; your entire program is undefined beyond this point.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node *tree_ptr;
typedef struct table * Table;
struct node
{
char* element;
tree_ptr left, right;
};
typedef struct table
{
tree_ptr head;
int tree_h;
}table;
char* key = NULL;
Table insert(char* insert_key,Table t)
{
int height = 0;
//tree_ptr ptr = t->head;
tree_ptr *ptr = &(t->head);
key = strdup(insert_key);
tree_ptr new_node = malloc(sizeof(struct node));
new_node->element = key;
new_node->left = NULL;
new_node->right = NULL;
if ( t->head==NULL ){
*ptr = new_node;
t->tree_h = 0;
printf("head:%s\n",t->head->element);
return t;
}
while(1){
if ( strcmp(insert_key, (*ptr)->element)<0 ){
if ( (*ptr)->left ==NULL ){
(*ptr)->left = new_node;
height++;
if ( height > t->tree_h)
t->tree_h = height;
break;
}
else{
(*ptr) = (*ptr)->left;
height++;
}
}
else if ( strcmp(insert_key, (*ptr)->element)>0 ){
if ( (*ptr)->right ==NULL ){
(*ptr)->right = new_node;
height++;
if ( height > t->tree_h)
t->tree_h = height;
break;
}
else{
(*ptr) = (*ptr)->right;
height++;
}
}
else break;
}
return t;
}
int main() {
Table t = malloc(sizeof(table));
t->head = NULL;
t = insert("one", t);
t = insert("two", t);
t = insert("three", t);
printf("%s\n",t->head->element);
return 0;
}
The above is a simplified program, some definition code is given, so I could not change the basic structure, like table, Table, node, tree_ptr, while others could be changed.
What I am trying to implement is a spellchecking, the table stored the head of the tree and some other properties of the tree(which is omitted here), the tree is implemented as an ordered binary tree.
I find that, insert() works well up to two times, after the (*ptr) = (*ptr)->right; the t->head is changed as well. So after using it two times, I lost the head of the tree.
How to modify my insert()?
To insert a node into a tree you first have to search for an empty leaf. Apart from this you do not modify t, so there is no need of writing it back by return value:
void insert( char* insert_key, Table t )
{
// serach empty leaf, where to insert the new node
tree_ptr *ptr = &(t->head); // start at head
while ( *ptr != NULL ) // end if empty leaf is found
{
int cmpRes = strcmp( insert_key, (*ptr)->element );
if ( cmpRes == 0 )
return; // insert_key already is member of tree
if ( cmpRes < 0 )
ptr = &((*ptr)->left); // step down to left child
else
ptr = &((*ptr)->right); // step down to right child
}
// create new node
tree_ptr new_node = malloc( sizeof(struct node) );
new_node->element = strdup( insert_key );
new_node->left = NULL;
new_node->right = NULL;
// place new node at empty leaf
*ptr = new_node;
}
With this recursive function you can print your tree:
void printTree( tree_ptr ptr )
{
if ( ptr == NULL )
return;
printTree( ptr->left );
printf( "%s\n", ptr->element );
printTree( ptr->right );
}
printTree( t->head );
And with this one you can free all nodes of your tree:
void deleteTree( tree_ptr ptr )
{
if ( ptr == NULL )
return;
deleteTree( ptr->left );
deleteTree( ptr->right );
free( ptr );
}
deleteTree( t->head );
t->head = NULL;
The problem is ptr is pointing to the address of the pointer to a struct node, instead of directly pointing to a struct node:
tree_ptr *ptr = &(t->head);
Then when iterating in the while loop, you aren't changing the pointer ptr, but the pointer it is pointing to, which is t->head:
(*ptr) = (*ptr)->left;
This overwrites the pointer, t->head on every iteration, effectively erasing the nodes that pointer pointed to, and leaking memory.
Instead use a normal pointer to the struct node:
struct node* iter = t->head;
...
if ( strcmp(insert_key, iter->element)<0 ){
...
}
else{
iter = iter->left;
....
And I would highly suggest removing those typedefs that hide the pointer, because they make the code hard to read and obfuscate the types, which is not desirable in this context:
typedef struct node *tree_ptr;
typedef struct table * Table;
Also note that if the loop finds a duplicate, the allocated node is not freed, leaking the memory.