C Error: `arithmetic on pointer to an incomplete type`

C Error: `arithmetic on pointer to an incomplete type`

如果我有定义:

typedef struct y_t *Y;

typedef struct x_t *X;    
struct x_t {
    Y *b;
    Y a;
    int size;
};

bY 类型的数组,大小为 size

我有

int func(X x) {    
    int diff = x->a - x->b[0];   // error here
    return diff;
}

假设 ab 数组中的一个元素,并且 func 需要 return a 在 [=13= 中的索引]数组。

但是我收到一个错误 arithmetic on pointer to an incomplete type(我正在使用 eclipse)。

我假设它有问题,因为它不知道数组的维度...那么我该如何修复 func

您收到该错误的原因是您试图索引一个不是数组的变量。当您取消引用数组时,就像您在此处所做的那样:

Y *b

您已经在结构定义中访问数组的第 0 个索引。所以只需将您的行更改为:

int diff = x->a - x->b;

消息...

arithmetic on pointer to an incomplete type

... 可能是因为 struct y_t 的声明在编译单元中此时不可见。 Y 的 typedef 作为这种结构的前向声明具有双重职责,但没有完整的声明,struct y_t 是一个不完整的类型。

x->ax->b[0]都是Y,a.k.a。 struct y_t *。它们之间的区别是根据指向结构的大小来定义的,但它的大小是未知的,因为它是一个不完整的类型。您需要为您正在做的工作提供 struct y_t 的声明。