单链表创建函数C

问题描述 投票:1回答:1

我目前正在尝试使函数create()用于单链列表,在该函数中,我应该传递无限数量的参数,并且它将作为节点的值传递参数。代码如下:

#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);
}

但是当我打印出来时,我只收到最后3个值(2,5,18)和一个数字-23791193490,每次都不同(我想这已经渗入了内存的另一部分)。如何正确执行此操作?

c singly-linked-list
1个回答
1
投票

您正在传递34作为count参数。正确的用法是:

sllnode* new_sllist = create(4,34,2,5,18);
© www.soinside.com 2019 - 2024. All rights reserved.