Copy elements of an array to a linked list in C

arrayscstructure

i have an array, i want to create a doubly linked list from it,by transferring my elements to the nodes. and linking them through pointers(prev and next)
what i did was

head = malloc(sizeof(struct))
head->prev=NULL
head->next=NULL
tail=head

for(i=0;i<num;i++){
    //copy data from arr[i] to tail
    temp=tail
    tail->next=malloc(sizeof(struct))
    tail=tail->next
    tail->prev=temp
}

now, how do i copy the data? temp, head and tail are pointers to structure

Best Answer

I guess you did not try writing and compiling. The elements of linked list should have at least some place to hold value from your array, let's say data of int type.

#include <stdio.h>
#include <malloc.h>
#define N 3

typedef struct a{
struct a* prev;
struct a* next;
int data;
}item;

int main(void)
{
item* head;
item* tail;
item* temp;
int num = N;
int data[N] = {1,2,3}; /*initialization*/
int i = 0;
head = (item*)malloc(sizeof(item));
head -> prev = NULL;
head -> next = NULL;
tail = head;
for(i = 0; i < num; i ++){
    temp = tail;
    tail -> next = (item*)malloc(sizeof(item));
    tail = tail -> next;
    tail -> next = NULL;
    tail -> data = data[i];
    tail -> prev = temp;
}
for(temp = head -> next; temp != NULL; temp = temp -> next) /*the following is for testing purpose*/
    printf("%d\t", temp -> data);
return 0;
}

Be aware that the head element does not contain what you want.