프린세스 다이어리

incompatible pointer types assigning to 'struct Node *' from 'Node *' [-Wincompatible-pointer-types] 해결 방법 본문

C, C++

incompatible pointer types assigning to 'struct Node *' from 'Node *' [-Wincompatible-pointer-types] 해결 방법

개발공주 2021. 10. 14. 22:33
728x90

 

연결 리스트 구조체를 만드는 과정에서 다음과 같은 에러가 발생했다.

 

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

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

Node *head; 

int main(void) 
{
    head = (Node*) malloc(sizeof(Node));
    
    Node *node1 = (Node*) malloc(sizeof(Node));
    node1 -> data = 1;
    Node *node2 = (Node*) malloc(sizeof(Node));
    node2 -> data = 2;

    head -> next = node1;
    node1 -> next = node2;
    node2 -> next = NULL;

    Node *cur = head -> next;

    while (cur != NULL)
    {
        printf("%d ", cur -> data);
        cur = cur -> next;
    } 
}

 

main.c:20:18: warning: incompatible pointer types assigning to 'struct Node *' from 'Node *'
      [-Wincompatible-pointer-types]
    head -> next = node1;
                 ^ ~~~~~
main.c:21:19: warning: incompatible pointer types assigning to 'struct Node *' from 'Node *'
      [-Wincompatible-pointer-types]
    node1 -> next = node2;
                  ^ ~~~~~
main.c:24:11: warning: incompatible pointer types initializing 'Node *' with an expression of type
      'struct Node *' [-Wincompatible-pointer-types]
    Node *cur = head -> next;
          ^     ~~~~~~~~~~~~
main.c:29:13: warning: incompatible pointer types assigning to 'Node *' from 'struct Node *'
      [-Wincompatible-pointer-types]
        cur = cur -> next;
            ^ ~~~~~~~~~~~
4 warnings generated.
1 2 %

 

이 문제는 컴파일러가 Node와 struct Node를 다른 타입으로 보기 때문에 워닝이 뜨는 것이다. typedef struct를 typedef struct Node로 고치면 해결이 된다.

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

 

728x90
Comments