如何将指针(指向结构)传递给函数?

时间:2014-08-18 17:13:46

标签: list function pointers struct linked-list

我想在C中创建一个链表,但是当我使用下面的代码时,gcc会抛出这个错误:

  

错误:' - >'的无效类型参数(有'结构列表')

代码是:

#include <stdio.h>
#include <stdlib.h> 

struct list{
    int age;
    struct list *next;
}; 

void create_item(int *total_items, 
                 struct list where_is_first_item,
                 struct list where_is_last_item)
{

    struct list *generic_item;
    generic_item = malloc(sizeof(struct list));
    printf("\nage of item %d: ", (*total_items)+1);
    scanf("%d", &generic_item->age);

    if(*total_items == 0){

        where_is_first_item->next=generic_item;
        where_is_last_item->next=generic_item;
        printf("\nitem created\n");
    }
    else{

        where_is_last_item->next=generic_item;
        printf("\nitem created\n");
    }

int main (void){
    struct list *where_is_first_item;
    struct list *where_is_last_item;
    int total_items=0;
    printf("\n\n\tCREATE A NEW ITEM\n");
    create_item(&total_items, where_is_first_item, where_is_last_item);
    total_items++;
    return 0;
}

2 个答案:

答案 0 :(得分:0)

void create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item) 

添加一个明星!

您还引用了无效内存,因为您已分配到generic_item,但随后引用where_is_first_itemwhere_is_first_item未分配给where_is_first_item = generic_item;。在使用where_is_first_item之前尝试main

您还会发现main函数中的指针保持不变,因为正在传递指针值。这里让人感到困惑/有趣:如果你想要修改struct_list **where_is_first_item中的指针,你需要将指针传递给指针:{{1}}。相信我,这很可能会让你感到高兴。

答案 1 :(得分:0)

您忘记将结构参数作为指针传递。

更改:

create_item(int *total_items, struct list where_is_first_item, struct list where_is_last_item)

到:

create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item)

相关问题