I am currently trying to make function create() for singly linked list, where I am supposed to pass unlimited amount of parameters and it will pass the parameters as nodes' values. The code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
//define sllnode struct
typedef struct sllist
{
int val;
struct sllist *next;
}
sllnode;
sllnode* create(int count, ...);
int main(void)
{
//here i try to print out values of this list
sllnode* new_sllist = create(34,2,5,18);
//print out values that I have assign using create() to test
for(int i = 0; i < 4; i++)
{
printf("%i\n",new_sllist[i].val);
}
}
//create function
sllnode* create(int count, ...)
{
va_list list;
int i;
int arr[count];
va_start(list, count);
//create array arr that have all the values passed as parameters
for(i = 0; i < count; i++)
{
arr[i] = va_arg(list,int);
}
//allocate memory for new singly linked list
sllnode *sllist = malloc(count * sizeof(sllnode));
//check if memory has been successfully allocated
if(sllist == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// loop through array arr and assign values to val and *next of each sllnode in new sllist
for (int j = 0; j < count; j++)
{
sllist[j].val = arr[j];
sllist[j].next = &sllist[j+1];
if(j == count - 1)
{
sllist[j].val = arr[j];
sllist[j].next = NULL;
}
}
return sllist;
free(sllist);
}
But when I print out I only receive the last 3 values (2,5,18) and a number -23791193490 which differs each time (I suppose this has seeped into another part of memory). How do I do this correctly?
countlist elements, which makes it difficult to free individual elements after manipulating the list in various ways. It is more conventional to allocate memory for each element individually.