【问题标题】:Singly linked list create function C单链表创建函数 C
【发布时间】:2020-09-29 17:51:55
【问题描述】:

我目前正在尝试为单链表创建函数 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,每次都不同(我想这已经渗入内存的另一部分)。我该如何正确地做到这一点?

【问题讨论】:

  • OT:您正在为count 列表元素分配单个内存块,这使得在以各种方式操作列表后难以释放单个元素。为每个元素单独分配内存更为传统。
  • 我认为您也不应该为此使用可变参数函数。它散发着语法固定的味道。
  • 感谢您的反馈。我的编码冒险已经快 3 周了,目前正在尝试按照 cs50 上的说明进行操作。您能否就如何使这一点变得更好并获得相同的结果提供一些建议(当传递无限参数然后创建相同数量的节点时)?

标签: c singly-linked-list


【解决方案1】:

您将 34 传递给 count 参数。正确的用法是:

sllnode* new_sllist = create(4,34,2,5,18);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多