I have to build a linked list with each node being an 16 byte array. Using code that works with single uint8_t values, I slightly modified it to accept the 16 bytes. However, whenever I print the list, all nodes are the last node added. What am I doing wrong?
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
struct array_deck
{
uint8_t *val;
struct array_deck *next;
};
struct array_deck *head = NULL;
struct array_deck *curr = NULL;
int sizeOfSet;
struct array_deck *create_list(uint8_t *val)
{
struct array_deck *ptr = (struct array_deck*)malloc(sizeof(struct array_deck));
if(NULL == ptr)
return NULL;
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
void print_list(void)
{
struct array_deck *ptr = head;
while(ptr != NULL)
{
printf("\n");
printf("actually added = ");
for (int i = 0; i < 16; i++) {
uint8_t blah = ptr->val[i];
printf("[%2i] ",blah);
}
ptr = ptr->next;
}
printf("\n");
return;
}
struct array_deck *add_to_list(uint8_t *data, bool add_to_end)
{
printf("array to be added = ");
for (int i = 0; i < 16; i++) {
printf("[%2X] ",data[i]);
}
if(NULL == head)
return (create_list(data));
struct array_deck *ptr = (struct array_deck*)malloc(sizeof(struct array_deck));
if(NULL == ptr)
return NULL;
ptr->val = data;
ptr->next = NULL;
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
int main(void)
{
printf ("# of arrays >> ");
scanf ("%d", &sizeOfSet);
uint8_t data[16];
for(int i = 1; i<=sizeOfSet; i++){
for (int j = 0; j < 16; j++) {
data[j] = i;
}
printf("\n");
add_to_list(data,true);
}
print_list();
return 0;
}
sample run that builds a linked list with 3 nodes:
# of arrays >> 3
array to be added = [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1] [ 1]
array to be added = [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2] [ 2]
array to be added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
actually added = [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3] [ 3]
Program ended with exit code: 0
ptr->val = val;. That means that all your nodes are pointing to the samedatathat was declared inmain. You need to allocate new memory and copy into the node. Not just point to the passed in buffer.