指针分配警告

时间:2017-09-04 14:13:06

标签: c pointers gcc

我有以下代码:

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

typedef struct node {
    int data;
    struct Node* next;
} Node;

typedef struct link_list {
    Node* HEAD;
} LinkList;

void kill(const char* message) {
    printf("ERROR: %s\n", message);
    exit(-1);
}

LinkList* createList() {
    LinkList* list = malloc(sizeof(LinkList));
    list->HEAD = NULL;
    return list;
}

Node* createNode() {
    Node* node = malloc(sizeof(Node));
    node->next = NULL;
    node->data = 0;
    return node;
}

void insert(LinkList* list, int data) {
    if(list == NULL)
        kill("Cannot insert. The given list is NULL.");

    Node* node = createNode();
    node->data = data;

    if(list->HEAD == NULL) {
        list->HEAD = node;
        return;
    }

    Node* it = list->HEAD;
    while(it->next != NULL) {
        it = it->next;
    }

    it->next = node;
}

void display(LinkList* list) {
    if(list == NULL)
        kill("The given link list has not been initialized.");

    Node* it = list->HEAD;

    if(list->HEAD == NULL)
        kill("The given link list is empty.");

    while(1 == 1) {     
        printf("%d ", it->data);
        it = it->next;
        if(it == NULL)
            break;
    }

    printf("\n");
}

void main() {
    int numbers;
    int data;

    LinkList* list = createList();

    printf("How many numbers?\n");
    scanf("%d", &numbers);

    for (int i = 0; i < numbers; ++i)
    {
        printf("Insert data of element %d: ", i + 1);
        scanf("%d", &data);

        insert(list, data);
    }

    display(list);
}

我收到以下警告:

Screenshot of Terminal

根据我的理解,给指针赋值似乎有问题。但据我所知,LHS和RHS类型似乎是一样的! (Node*)

是否与next定义为struct Node* next并且我将其分配给Node*的值这一事实有关?

3 个答案:

答案 0 :(得分:3)

Node定义结束之前,Node类型未知:

typedef struct node {
    int data;
    struct Node* next;
} Node;

将其更改为:

typedef struct node {
    int data;
    struct node* next;
} Node;

答案 1 :(得分:3)

更改

typedef struct node {
    int data;
    struct Node* next;
} Node;

typedef struct node {
    int data;
    struct node* next;
} Node;

答案 2 :(得分:0)

这样可以正常工作,

new injectedComp.render()