c - 结构指针初始化错误

标签 c struct linked-list

我有这个程序,我正在尝试修改它,但我不明白为什么声明: 结构链接 * temp = cap; 不打印我分配给链接列表的号码。 提前致谢!

struct Link
{
    int data;
    struct Link *urmatorul;
};

void Insert(Link * cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(cap != NULL)
        temp->urmatorul = cap;
    cap = temp;
}

void Print(Link * cap)
{
    struct Link *temp = cap;
    printf(" %d", cap->data);
    printf("The number is: ");
    while(temp != NULL)
    {
        printf(" %d", temp->data);
        temp = temp->urmatorul;
    }
    printf("\n");
}

int main()
{
    struct Link * cap;
    cap = NULL;
    printf("How many numbers? \n");
    int x, n, i;
    scanf(" %d", &x);
    for(i = 0; i < x; ++i)
    {
        printf("Enter the number: \n");
        scanf("%d", &n);
        Insert(cap, n);
        Print(cap);
    }
    return 0;
}

最佳答案

你需要通过引用传递 Link * 来改变它,这是一个 Link **

void Insert(Link **cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(*cap != NULL)
        temp->urmatorul = *cap;
    *cap = temp;
}

并在你的 main(...) 中使用

Insert(&cap, n);

或者您可以像这样从您的 Insert(...) 返回新的 Link *

Link * Insert(Link * cap, int n)
{
    struct Link * temp = (Link*)malloc(sizeof(struct Link));
    temp->data = n;
    temp->urmatorul = NULL;
    if(cap != NULL)
        temp->urmatorul = cap;
    return temp;
}

并在你的 main(...) 中使用

cap = Insert(cap, n);

关于c - 结构指针初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651991/

相关文章:

c - 自动为 C 结构分配内存

C++ 问题: "Unresolved external ' UberList<int>::Iter::Iter( )' referenced from C:\USERS\HOME\CPPTEST\UBERLIST.OBJ"

c++ - 是否存在通过引用选择元素和通过指针操作选择元素都有效的情况?

c - strcpy 使程序崩溃

xml - 解析动态 XML

c - 初始化一个结构体数组,里面有数组

c - 排序简单链表 - C

java - 如何在不知道其真实类型的情况下比较两个对象

c - 拆分字符串并将各个部分转换为十六进制

C 编程 while 循环和数组结构