1

我正在尝试使用不透明的数据类型来了解它们。主要问题是我不断收到“不完整”错误。

主程序

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

int main()
{
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}

fnarpishnoop.c

#include "blepz.h"

struct noobza {
    int fnarp;
};

void setfnarp(struct noobza x, int i){
    x.fnarp = i;
};

int getfnarp(struct noobza x){
    return x.fnarp;
};

blepz.h

struct noobza;

void setfnarp(struct noobza x, int i);

int getfnarp(struct noobza x);

struct noobza GOO;

我显然不明白这里的某些东西,我希望有人可以帮助我弄清楚不透明数据类型是如何实现的,如果它们的全部意义在于你很难找到它们的实际代码。

4

1 回答 1

3

struct正如您已经提到的,使用您尚未声明其内容的 a 会产生“不完整类型”错误。

相反,使用指向 的指针struct和返回指向 的指针的函数struct,如下所示:

struct noobza;

struct noobza *create_noobza(void);

void setfnarp(struct noobza *x, int i);

int getfnarp(struct noobza *x);

struct noobza *GOO;

...

#include <stdlib.h>
#include "blepz.h"

struct noobza {
    int fnarp;
};

struct noobza *create_noobza(void)
{
    return calloc(1, sizeof(struct noobza));
}

void setfnarp(struct noobza *x, int i){
    x->fnarp = i;
};

int getfnarp(struct noobza *x){
    return x->fnarp;
};

...

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

int main()
{
    GOO = create_noobza();
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}
于 2019-08-10T23:05:32.617 回答