有关取消引用结构指针的问题

时间:2009-11-06 14:42:43

标签: c pointers structure dereference

我正在编译这段代码,我得到编译错误,说“解除指向不完整类型的指针”。 我得到了最后一个print语句的错误,在此之前我尝试指向(* temp)。 num到b的地址

void main()
{

    struct {
        int xx;
        char *y;
        int * num;
        struct x *next;
    }x;

    struct x* temp;
    int b = 10;

    temp = ((struct x *)malloc(sizeof(x)));

    (*temp).num = &b;

    x.next = temp ;

    printf(" %d\n",temp->num, x.next->num);

}

5 个答案:

答案 0 :(得分:5)

问题在于声明:

struct {
   ...
} x;

定义一个未命名的实例'x' - 不是命名类型'x'。

所以当你从里面引用'struct x'时,所有编译器都知道你需要一些类型'x'的指针 - 你稍后会定义它(你永远不会这样做)。

要定义命名类型'x',您需要:

struct x {
   ...
};

答案 1 :(得分:0)

我认为你的意思是:

struct x {
  int xx;
  char *y;
  int * num;
  struct x *next;
}x;

您引用的“结构标记”在您使用struct x的任何位置时都未定义。您无法引用变量x的类型。由于您要使用struct x引用它,因此必须定义struct标记。

答案 2 :(得分:0)

我认为你的结构在完全定义之前就引用了它。

特别是,你的结构没有名字; “x”是具有这种结构的变量的名称,但没有类型名称。

只需声明“struct x { ... } x”,就可以了。

答案 3 :(得分:0)

除了Draemon写的关于struct x {...} x的内容之外,我冒昧地纠正了其他一些小问题,例如printf()

void main()
{
  struct x {
    int xx;
    char *y;
    int *num;
    struct x *next;
   } x;
   struct x* temp;
   int b = 10;
   temp = ((struct x *)malloc(sizeof(struct x)));
   (*temp).num = &b;
   x.next = temp ;
   printf("%d %d\n",*temp->num, *x.next->num);
}

出于好奇:你想要达到什么目的?

答案 4 :(得分:0)

请注意,void main()从未成为C或C ++中main的有效原型。

如果您想指向struct中宣布的struct,则需要标记structtypedef有时很有用,但不是必需的。

请研究您的代码与以下内容之间的差异,并了解为何存在差异。这将有助于你学习。因此,请阅读C FAQ list(例如,请参阅Structures, Unions, and Enumerations

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

int main(void) {
    int b = 10;

    typedef struct x_struct {
        int xx;
        char *y;
        int *num;
        struct x_struct *next;
    } x;

    x *temp = malloc(sizeof(*temp));
    if ( !temp ) {
        return EXIT_FAILURE;
    }

    temp->num = &b;
    temp->next = temp;

    printf("%d %d\n", *(temp->num), *(temp->next->num));
    return 0;
}