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

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

我正在尝试声明一个结构并在多个文件中使用它,但出现了一个我无法弄清楚的错误。下面发布了示例代码。

在test.h

#ifndef TEST_H
#define TEST_H

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

#endif

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

在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() 打印出 0 2 4 6 8 10 12 14 16 18。为什么 myprint( 函数不起作用但 printf 语句不起作用?为什么可以将它传递给函数但不能在 main 中使用它?谢谢。

目前main()只知道struct mystruct是一个类型,但不知道它的内部结构,因为你把它隐藏在test.c里了。

所以你需要移动这个定义:

struct mystruct {
    int *myarray;
};

从 test.c 到 test.h,以便 main() 可见。

注意:您在这里所做的是不透明类型 的典型示例。当您想从将要调用您的 API.

的代码中隐藏实现细节时,这可能是一种非常有用的技术。

Main.c 不知道 mystruct 结构的内容。尝试移动这些行:

struct mystruct {
    int *myarray;
};

从 test.c 到 test.h。

虽然你在这里,但我认为你的意思是 "int myarray" 而不是 "int *myarray"。