I am trying to implement the dynamic linked list with the below dataset.
typedef struct node {
uint8_t item1;
uint8_t item2;
char* key;
struct node *next;
} node;
node *nodes = NULL;
static node* find_by_item1(uint8_t item1) {
node *sl = nodes;
while(sl && sl->item1 != item1)
sl = sl->next;
return sl;
}
void createNode(char* key, uint8_t item1, uint8_t item2){
node *sl = find_by_item1(item1);
if(sl){
//Do Process further if the key is already entered again
return;
}
node *sl = malloc(sizeof(node));
if(!(sl = malloc(strlen(key)+1))){
free (sl);
return;
}
//memset(sl, 0, sizeof(*sl));
//Add the data
sl->item1 = item1;
sl->item2 = item2;
strcpy (sl->key, key);
sl->next = nodes;
nodes = sl;
}
void printNode(){
Node *sl;
for(sl = nodes; NULL != sl; sl = sl->next){
printf("\nNode %s %d %d", sl->Key, sl->item1, sl->item2);
}
}
void main(){
for (uint8_t i = 1; i <= 4; i++) {
char key_name[12] = {0};
sprintf(key_name, “Key-%d”, i);
switch (i) {
case 1:
createNode(key_name, 1, 2);
break;
case 2:
createNode(key_name, 3, 4);
break;
case 3:
createNode(key_name, 5, 6);
break;
case 4:
createNode(key_name, 7, 8);
break;
default:
break;
}
}
printNode();
}
}
I have tried to implement this based on my research but somehow unable to achieve the result that I was intending. Have spent about last 3-4 days constantly thinking and implementing and re-implementing this but I seems to be missing something obvious.
My program fails at 1st line in "find_by_item1" while(sl && sl->item1 != item1)
Any pointers will be helpful.
---Update
I have been trying to understand the absurd error and seems the error was something related to the NULL Pointer Reference.
Commenting the line memset(sl, 0, sizeof(*sl));
allowed to start making the progress again.
However, now, when I try to print the link list below is the input and output:
Input:
Key-1 1 2
Key-2 3 4
Key-3 5 6
Key-4 7 8
Output:
Node Key-4 1 2
Node Key-4 3 4
Node Key-4 5 6
Node Key-4 7 8
Now I am not sure how can I fix this code to retain the correct Key against each items.
Help pls.
Thanks, Kunjal