我编写了一个c程序来创建一个简单的链表,当我尝试将struct变量的指针等同于下一个的地址时,编译器将引发错误。你能帮我解决吗?说int*不能转换为list。这是代码片段:

struct list
{
    int n;
    struct list *p;
};

void main()
{
    struct list item0, item1;
    item0.n=1;
    item0.p=&item1.n;//The compiler is throwing an error here. Says they are two incompatible types
    item1.n=2;
    item1.p=NULL;
}

最佳答案

编译器将引发错误,因为&item1.n被编译器读取为(&item1).n,这是没有意义的。因为是C语言,所以&运算符的优先级高于.

由于p是list *,您应该这样写:

item0.p = &item1;


因为n是结构的第一个元素,所以您也可以编写(在C中,因为在不强制转换为void *的情况下它不是有效的C ++)item0.p = &(item1.n),但这很不好,因为您将int的指针分配给list的指针。

如果以后要同时打印两者,则打印item0.nitem0.p->n的值,因为它们都是整数。正如我上面所写的,您可以写int i = *((int *) item0.p),但这很丑陋。编写类似的代码很快就会导致难以理解和难以维护的代码。

10-08 07:11