1

我无法将新列表插入到我的结构中。有人可以帮帮我吗?谢谢!:) 这是我的代码和错误:

编译后报错:

27:9:错误:从类型“node_t * {aka struct _node_t *}”分配给类型“node_t {aka struct _node_t}”时类型不兼容

代码:

typedef struct _node_t {
    double d;
    struct _node_t *next;
    } node_t;

void print_list (node_t *l) {
    node_t *curr = l;
    printf("[");

    while (curr != NULL) {
        if (l != curr) printf (",");
        printf("%4.1f",curr->d);
        curr = curr->next;
    }

    printf("]\n");
}

node_t *insert (node_t *l, double d) {
    node_t *new_node;
    new_node = (node_t *) malloc (sizeof(node_t));

    if (new_node == NULL) {
        printf("insert: error: no space left\n");
        return l;
    }

    new_node->d = d;
    new_node->next = l;
    return new_node;
}

int main (void) 
{   
    node_t n1;

    print_list(&n1);
    n1=insert(n1,10);
}
4

1 回答 1

1

该函数insert的返回类型node_t *是指针类型。

但是,在 main 中,您试图将返回的指针分配给非指针类型的对象。

node_t n1;
//...
n1=insert(n1,10);

此外,该对象n1未初始化。

你需要写在 main

node_t *n1 = NULL;
print_list( n1 );
n1=insert( n1, 10 );

似乎最好在 main 中交换最后两个语句,例如

node_t *n1 = NULL;
n1=insert( n1, 10 );
print_list( n1 );
于 2019-10-03T14:36:25.360 回答