This is the code for a doubly linked list where the values are inserted at the beginning. The code keeps returning the head values instead of the actual values.
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;
void InsertatBegin(int a){
struct Node* NewNode = (struct Node*)(malloc(sizeof(struct Node*)));
NewNode->data = a;
NewNode->next = NULL;
NewNode->prev = NULL;
if (head == NULL){
head = NewNode;
return;
}
NewNode->next = head;
head->prev = NewNode;
head = NewNode;
}
void traverse(){
struct Node* temp = head;
while (temp != NULL) {
if (temp->next == NULL) {
printf(" %d->NULL", temp->data);
}
else {
printf(" %d->", temp->data);
}
temp = temp->next; // Traversing the List till end
}
printf("\n");
}
int main(){
head = NULL;
InsertatBegin(5);
InsertatBegin(6);
InsertatBegin(7);
InsertatBegin(8);
InsertatBegin(9);
traverse();
}
This is the output for the code, it seems to print the address of the nodes instead of the values stored in the Node.data structure.
Output:
752904464-> 752904448-> 752904432-> 752904416-> 5->NULL
CodePudding user response:
struct Node* NewNode = (struct Node*)(malloc(sizeof(struct Node*)));
First step is to remove some excess parentheses!
struct Node* NewNode = (struct Node*) malloc( sizeof struct Node* );
Less code makes it easier to spot what may not be correct... So let's fix that.
struct Node* NewNode = (struct Node*) malloc( sizeof struct Node );
You probably shouldn't be "casting" the return from malloc( )
unless you're using a very old compiler.
struct Node* NewNode = malloc( sizeof struct Node );
struct Node
is repeated, and may create a hard-to-find bug if the code is altered carelessly. How much space do we want? Enough to point at with our pointer!
struct Node* NewNode = malloc( sizeof *NewNode );
Easier to read?
And, wars have been fought over this, but this example shows the benefit of shifting the '*' in the declaration of a pointer.
struct Node *NewNode = malloc( sizeof *NewNode );
NewNode
is first-and-foremost a pointer. It just happens to be used to point an instance of a "struct Node".
CodePudding user response:
As mentioned in the comments, you should allocate memory as Node
not Node*
.
struct Node* NewNode = (struct Node*) malloc(sizeof(struct Node));
It allocates enough memory for a Node structure and returns a pointer to that allocated memory. You can take a look at this