简体   繁体   English

C将指针解引用为不完整类型时出错

[英]C Error for dereferencing pointer to incomplete type

I have some issues with a main file.I have a matrix of structures (theoretically) and i want to modify all my "p" parameters in all the structures. 我的主文件有一些问题。我有一个结构矩阵(理论上),我想修改所有结构中的所有“ p”参数。 This is the main file: 这是主文件:

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);
}

And this is another file which contains structures definiton and generate function: 这是另一个包含结构定义和生成函数的文件:

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;
}

Any ideas? 有任何想法吗?

You are seeing the error because struct is part of the type in C, so you have to use struct newline in struct PQ. 您会看到此错误,因为struct是C中类型的一部分,因此您必须在struct PQ中使用struct newline Another way is to use typedef to create type alias: 另一种方法是使用typedef创建类型别名:

typedef struct newline {
    int p;
} newline;

The way to access struct's member is use . 访问struct成员的方法是use。 on struct, use -> on pointer to struct, so use queue->mem[i][j].p instead. 在结构上,使用->指向结构的指针,因此请使用queue->mem[i][j].p

There are other problems. 还有其他问题。

You cannot dereference an uninitialized pointer, it yields undefined behavior: 您不能取消引用未初始化的指针,它会产生未定义的行为:

PQ *newQ;

should be: 应该:

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

You should allocate with correct indirections: 您应该使用正确的间接分配:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM