Warning on pointer assignmentAsk Question

问题:

I have the following code:

#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);
}

And I am getting the following warnings:

Screenshot of Terminal

From what I understand, there seems to be a problem with assigning value to pointers. But as far as I see it, the LHS and RHS types seems to be the same! (Node*).

Does it has something to do with the fact that next is a defined as struct Node* next and the value I am assigning it to is Node*?

回答1:


Change

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

into

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

回答2:


The type Node is unknown until the end of the Node definition:

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

Change it to:

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

回答3:


this will work fine,

typedef struct node {
    int data;
    struct node* next;
} Node;
标签: pointers gcc
© 2014 TuiCode, Inc.