2

浏览了许多与此相关的其他 SO 帖子,但没有一个能够帮助我。所以,我定义了以下结构:

 typedef struct
    {
    int created;
    double data;
    int timeLeft;
    int destination;
}dataPacket;

typedef struct
{
    dataPacket *array;
    int currIndex;
    int firstIndex;
    int nextTick;
    int maxLength;
    int length;
    int stime;
    int total;


}packetBuffer;

typedef struct{
    int mac;
    struct wire *lconnection;
    struct wire *rconnection;
    int numRecieved;
    struct packetBuffer *buffer;
    int i;
    int backoff;
}node;

typedef struct{
    float length;
    float speed;
    int busy;
    struct dataPacket *currPacket;
    struct node *lnode;
    struct node *rnode;
}wire;

然后我尝试使用以下功能:

    int sendPacket(node *n, int tick)
{
    if(n->buffer->length > 0)
    {
        if(n->backoff <= 0)
        {
            if (n->lconnection->busy != 0 || n->lconnection->busy != 0)
            {
                n->i++;
                n->backoff = (512/W * genrand()*(pow(2,n->i)-1))/TICK_LENGTH;
            }
            else
            {
                n->lconnection->busy = 1;
                n->rconnection->busy = 1;
                n->lconnection->currPacket = n->buffer[n->buffer->currIndex];
                n->rconnection->currPacket = n->buffer[n->buffer->currIndex];
            }
        }
        else
        {
            n->backoff--;
        }
    }
}

每次我尝试访问缓冲区、lconnection 或 rconnection 的成员时,都会收到标题中描述的错误。

4

2 回答 2

5
struct packetBuffer *buffer;

You've defined a type packetBuffer (a typedef for an otherwise anonymous struct).

You haven't defined struct packetBuffer.

In the absence of an existing type struct packetBuffer, the compiler treats it as an incomplete type, assuming that you'll complete it later. The declaration

struct packetBuffer *buffer;

is perfectly legal, but you can't dereference buffer unless the type struct packetBuffer is visible.

Just drop the struct keyword.

(My personal preference is to drop the typedef and consistently refer to struct types as struct whatever, but that's a matter of style and taste.)

于 2013-03-11T18:12:26.807 回答
1

以下:

typedef struct { int x; char *y; ... } my_struct;

为匿名结构创建标识符。为了让结构引用自身的实例,它不能是“匿名的”:

typedef struct my_struct {
    int x;
    char *y;
    struct my_struct *link
    ....
} my_struct_t;

这意味着my_struct_t现在是类型struct my_struct,而不仅仅是匿名结构。另外,请注意struct my_struct可以在其自己的结构定义中使用。这对于匿名结构是不可能的。

最后一个问题是, my_structinstruct my_struct与 .in 位于不同的“命名空间”中my_struct_t。这有时用于简化(或混淆)代码中的内容,如下所示:

typedef struct my_struct {
    int x;
    char *y;
    struct my_struct *link
    ....
} my_struct;

现在我可以my_struct在代码中的任何地方使用,而不是struct my_struct.

最后,您可以将 typedef 与结构定义分开以达到相同的效果:

struct my_struct {
    int x;
    char *y;
    struct my_struct *link;
    ....
};
typedef struct my_struct my_struct;

正如 David R.Hanson 的C 接口和实现中所指出的,“这个定义是合法的,因为结构、联合和枚举标签占据了与变量、函数和类型名称空间分开的相同名称空间。”

于 2013-03-11T19:01:41.243 回答