Why can't I create an opaque data type?

為{幸葍}努か 提交于 2021-02-10 15:55:02

问题


I'm trying to experiment with opaque data types to get an understanding of them. The main problem is that I keep getting an 'incomplete' error.

main.c

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

I clearly don't understand something here and I was hoping someone could help me figure out how opaque data types are implemented if the whole point of them is that you have a hard time finding actual code for them.


回答1:


Using a struct that you haven't declared the contents of gives an "incomplete type" error, as you have already mentioned.

Instead, use a pointer to the struct and a function that returns a pointer to the struct, like this:

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


来源:https://stackoverflow.com/questions/57446226/why-cant-i-create-an-opaque-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!