Reputation: 31
I'm trying to put integer data from each node in a queue into an array called arr. The data for each node is inputted by the user, say there's 5 nodes, and has 1 2 3 4 5, where node 1 stores a value of 1 and node 5 stores a value of 5. My code is below:
typedef struct linkedList {
int val;
struct linkedList *next;
} list;
I've tried doing the following but I'm getting a few warnings when I compile the code, I only included the body of the function and not the header or prototype and such.
int i;
int *arr;
list *node = NULL;
for(i = 0; i < 5; i++) {
arr[i] = (int*)malloc(sizeof(int));
arr = node->id;
node = node->next;
}
The errors that I get are: warning: assignment to ‘int *’ from ‘int’ makes pointer from integer without a cast
and warning: variable ‘arr’ set but not used
How do I actually get the data from the queue into an array so that the array is arr[0]=1
and arr[4]=5]
? Thanks.
Upvotes: 1
Views: 192
Reputation: 3613
Assuming you already have your linked list allocated correctly and you know the number of nodes (since you didn't post the code for your linked list) then your copy to array function should look like this.
int* copylist(struct LinkedList* ls,int numberofnodes){
int* arr = malloc(sizeof(int)*numberofnodes);
for(int index = 0; index < numberofnodes; ++index){
arr[index] = ls->val;
ls = ls->next;
}
return arr;
}
Upvotes: 2