简体   繁体   English

多个文件中的c struct错误:将指针解引用为不完整类型

[英]c struct in multiple file error: dereferencing pointer to incomplete type

I am trying to declare a struct and use it in multiple files and I am getting an error that I cannot figure out. 我试图声明一个结构,并在多个文件中使用它,但遇到了我无法弄清的错误。 Sample code is posted below. 示例代码发布在下面。

in test.h 在test.h中

#ifndef TEST_H
#define TEST_H

struct mystruct;
struct mystruct *new_mystruct();
void myprint(struct mystruct*,int);

#endif

int test.c int test.c

#include "test.h"

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

struct mystruct {
    int *myarray;
};

struct mystruct *new_mystruct(int length)
{
    int i;

    struct mystruct *s;
    s = malloc(sizeof(struct mystruct));
    s->myarray = malloc(length*sizeof(int));

    for(i = 0; i < length; ++i)
        s->myarray = 2*i;

    return s;
}

in main.c 在main.c中

#include "test.h"

#include <stdio.h>

int main()
{
    int len = 10;

    struct mystruct *c = new_mystruct(len);
    myprint(c, len);

    printf("%f", c->myarray[3]); // error: dereferencing pointer to incomplete type

    return 0;

myprint() prints out 0 2 4 6 8 10 12 14 16 18. why doesn't the myprint(function work but the printf statement doesn't? why is it ok to pass it into a function but not use it in main? Thanks. myprint()打印出0 2 4 6 8 10 12 14 16 18.为什么myprint(函数不起作用,但printf语句不起作用?为什么可以将其传递给函数但不在main中使用它呢?谢谢。

Currently main() only knows that struct mystruct is a type, but it doesn't know anything about its internal structure, because you've hidden it in test.c. 当前main()仅知道struct mystruct是一个类型,但对其内部结构一无所知,因为您已将其隐藏在test.c中。

So you need to move this definition: 因此,您需要移动以下定义:

struct mystruct {
    int *myarray;
};

from test.c to test.h, so that it's visible to main() . 从test.c到test.h,以便对main()可见。

Note: what you're doing here is a classic example of an opaque type . 注意:您在这里所做的是不透明类型的经典示例。 This can be a very useful technique when you want to hide implementation details from code that is going to be calling your API. 当您想从将要调用您的API的代码中隐藏实现细节时,这可能是一种非常有用的技术。

Main.c doesn't know the contents of the mystruct structure. Main.c不知道mystruct结构的内容。 Try moving these lines: 尝试移动这些行:

struct mystruct {
    int *myarray;
};

from test.c to test.h. 从test.c到test.h。

While you're at it, I think you mean "int myarray" not "int *myarray". 当您使用它时,我认为您的意思是“ int myarray”而不是“ int * myarray”。

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

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