AlameerAshraf AlameerAshraf - 1 year ago 70
C Question

add new node to an exisiting linked list in c

when I'm trying to add a new node to my linked list the compiler stop working and fails to add the node , I can't find out the problem is it in the logic or in the syntax

struct Record* CreateNode()
struct Record* PointerToRecord ;
PointerToRecord = (struct Record*) malloc(sizeof(struct Record*));
PointerToRecord -> C = FillDataOfContacts();
PointerToRecord -> Next = NULL;
PointerToRecord -> Prev = NULL;
return PointerToRecord ;

struct Record* AddNode()
if (Head == NULL && Tile == NULL)
Head = Tile = CreateNode();
struct Record* Pointer ;
Pointer = CreateNode();
Tile -> Next = Pointer ;
Pointer -> Prev = Tile ;
Pointer -> Next = NULL;
Tile = Pointer ;

Answer Source

In your struct Record* CreateNode() function, you have:

PointerToRecord = (struct Record*) malloc(sizeof(struct Record*));

Here you are not assigning enough memory to store a struct record instead you are assigning memory to store a struct record*

try assigning this way:

PointerToRecord = (struct Record*) malloc(sizeof(struct Record));

Additionally, you need not cast the return value of malloc : Here's why (click)

so you can allocate your pointer in the following manner

PointerToRecord = malloc(sizeof(struct Record));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download