2012-07-18 682 views
3

我写在C 列表下面是源:错误:不兼容的类型参数

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


struct list { 
int value; 
struct list *next; 
}; 

typedef struct list ls; 



void add (ls **head, ls **tail, int val) 
{ 
ls *new, *tmp1, *tmp2; 

if (NULL == *head) 
{ 
    new = (ls*)malloc(sizeof(ls)); 
    *head = new; 
    *tail = new; 
    new->value = val; 
    new->next = NULL; 

    return; 
} 

else 
{ 
    tmp1 = *head; 
    tmp2 = tmp1->next; 
    while (tmp2 != NULL) 
    { 
     tmp1 = tmp2; 
     tmp2 = tmp1->next; 
    } 

    new = (ls*)malloc(sizeof(ls)); 
    new->value = val; 
    new->next = NULL; 
    *tail = new; 

    return; 
} 
} 



void show (ls **head, ls **tail) 
{ 
int i; 
ls *tmp; 

while (tmp->next != NULL) 
{ 
    printf("%d: %d", i, tmp->value); 
    i++; 
    tmp=tmp->next; 
} 

return; 
} 



int main (int argc, char *argv[]) 
{ 
ls *head; 
ls *tail; 
int n, x; 

head = (ls*)NULL; 
tail = (ls*)NULL; 

printf("\n1. add\n2. show\n3. exit\n"); 
scanf("%d", &x); 
switch (x) 
{ 
    case 1: 
     scanf("%d", &n); 
     add(*head, *tail, n); 
     break; 

    case 2: 
     show(*head, *tail); 
     break; 

    case 3: 
     return 0; 

    default: 
     break; 
} 

return 0; 
} 

当我用gcc

gcc -o lab5.out -Wall -pedantic lab5.c 

编译它,我得到奇怪的错误:

lab5.c: In function ‘main’: 
lab5.c:84:3: error: incompatible type for argument 1 of ‘add’ 
lab5.c:16:6: note: expected ‘struct ls **’ but argument is of type ‘ls’ 
lab5.c:84:3: error: incompatible type for argument 2 of ‘add’ 
lab5.c:16:6: note: expected ‘struct ls **’ but argument is of type ‘ls’ 
lab5.c:88:3: error: incompatible type for argument 1 of ‘show’ 
lab5.c:52:6: note: expected ‘struct ls **’ but argument is of type ‘ls’ 
lab5.c:88:3: error: incompatible type for argument 2 of ‘show’ 
lab5.c:52:6: note: expected ‘struct ls **’ but argument is of type ‘ls’ 

对我来说,一切都OK了...

参数类型为ls**,而不是编译器说的ls

有人看到什么可能是错的?

PS。我知道这是没有必要给*tail作为参数,它是未使用的,但是这将是的,因为我想开发这个“计划” ......

+0

你需要''而不是'*'在通话中。 – 2012-07-18 16:33:03

+0

当然......它解决了这个问题。非常感谢... – kostek 2012-07-18 16:39:43

回答

3

正如Daniel在他的评论中所说的,codaddict在他的回答中说,使用&而不是*会给你想要的。这里有一些解释,以帮助你记住。

*de-引用它附加的内容,意味着它将变量看作是一个指针并给出该地址的值。

&通过参考,这意味着它给出了值的存储地址,或者说,将一个指针传递给变量。

既然你想一个指针传递给变量的头部和尾部,你想通过他们为&head&tail,它给你的价值观**head**tail在另一端。在你习惯之前,它似乎是反直觉的。

+0

是的...我现在明白了... – kostek 2012-07-18 17:30:29

+0

@kostek酷。对不起,如果我遇到居高临下。通过互联网很难阻止。我只是想确保我完全解释它,因为当我刚刚学习时,我个人遇到了问题。祝你的代码好运! – 2012-07-18 17:33:17

+0

不,没关系。感谢您的完整解释。 – kostek 2012-07-18 18:39:27

1
add(*head, *tail, n); 

应该是:

add(&head, &tail, n); 

既然你需要将头部和尾部指针的地址传递给函数。

需要对调用show函数进行类似修复。