C取消引用指向不完整类型的指针时出错

C Error for dereferencing pointer to incomplete type

本文关键字:类型 指针 出错 引用 取消      更新时间:2023-10-16

我的主文件有一些问题。我有一个结构矩阵(理论上),我想修改所有结构中的所有"p"参数。这是主文件:

int main(int argc, char** argv) {
int i, j;
struct PQ *queue;
queue = createQ(5);
for (i = 0; i <= 5; i++) {
    for (j = 0; j = 20; j++);
    queue->mem[i][j].p = 1;
}
for (i = 0; i <= 5; i++) {
    puts("n");
    for (j = 0; j <= 20; j++);
    printf("%d ",queue ->mem[i][j].p);
}

return (EXIT_SUCCESS);
}

这是另一个包含结构定义和生成函数的文件:

typedef struct newLine{
    unsigned p;
} newLine;

struct PQ{
    struct newLine ** mem;
};
struct PQ *createQ(unsigned min){
    int i=0;
    struct PQ *newQ = malloc(sizeof(PQ));
    newQ->mem = malloc(min*sizeof(newLine *));
    for(i=0;i<=min;i++){
        newQ->mem[i]=calloc(20,sizeof(newLine));
    }
    return newQ;
}

有什么想法吗?

您看到的错误是因为struct是C中类型的一部分,所以您必须在struct PQ中使用struct newline。另一种方法是使用typedef创建类型别名:

typedef struct newline {
    int p;
} newline;

访问结构的成员的方法是使用。在struct上,在指向struct的指针上使用->,因此请改用queue->mem[i][j].p

还有其他问题。

你不能取消引用未初始化的指针,它会产生未定义的行为:

PQ *newQ;

应该是:

struct PQ *newQ = malloc(sizeof(struct PQ));

您应该使用正确的间接寻址进行分配:

newQ->mem = malloc(min * sizeof(newline*));
for(int I = 0;i < min; i++){
    newQ->mem[i] = calloc(20, sizeof(newLine));
}