2015-01-17 2 views
1

나는 C에 비교적 새로운 해요이 두 구조체 사용하여 목록의 시작 부분에 노드를 삽입하는 함수를 작성하려고 :"호환되지 않는 포인터 유형 [기본적으로 활성화 됨]에서 할당"?

typedef struct singly_linked_list_node { 
    char *data; 
    struct singly_linked_list_node *next; 
} node; 

typedef struct singly_linked_list_head { 
    struct node *first; 
    struct node *last; 
    int size; 
} sin_list; 

내 기능

void insert_at_start(sin_list* list, char *str) 
{ 
    int length; 
    node *newnode; 
    newnode = malloc(sizeof(node)); 
    length = strlen(str) + 1; 
    newnode->data = malloc(sizeof(length)); 
    strcpy(newnode->data, str); 
    newnode->next = list->first; 
    list->first = newnode; 
    if (list->last == NULL) list->last = newnode; 
} 

입니다 언제 컴파일 난 "마지막으로 3 라인에 대한 호환되지 않는 포인터 유형 [기본적으로 활성화]에서 경고"할당 그래서 분명히 뭔가 빠졌어요.

+2

** node ** 및 ** list **의 유형이 – user7

+1

과 일치하지 않습니다. newnode-> data = malloc (sizeof (length)); -> newnode-> data = malloc (length); ' – BLUEPIXY

+0

왜 구조체가 필요합니까? struct singly_linked_list_head ** – user7

답변

1

struct singly_linked_list_head의 정의를 사용하면 struct 유형에 대해 두 개의 암시 적 전달 선언을 사용합니다. 이들은

struct node *first; 
struct node *last; 

입니다. node에 대한 typedef가 있습니다. 유형 struct node은 결코 해결되지 않지만 포인터 만 사용하는 한 컴파일러는 괜찮습니다. 언어 C에는 구조체 이름과 typedef에 대해 두 개의 고유 한 이름 공간이 있습니다. 당신이 메모리를 할당 할 때 str의 길이를 사용해야하고 변수 length의 크기가 data의 메모리를 할당 할 수 없습니다

typedef struct singly_linked_list_head { 
    node *first; 
    node *last; 
    int size; 
} sin_list; 

편집을 :

은 형식 정의를 사용 하여 코드를 수정 :

length = strlen(str) + 1; 
newnode->data = malloc(sizeof(length)); 

변경하려면 다음

length = strlen(str) + 1; 
newnode->data = malloc(length); 
관련 문제