Re: Anonymous structures

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Raseel Bhagat wrote:

> > No. An anonymous structure has an unknown size, so the compiler cannot
> > generate code to copy them.
> >
> > Anonymous structures are only useful as pointer targets, i.e.
> > "struct A *foo". You can pass around pointers to structures without
> > knowing the size of the structure, although you can't dereference them.
> 
> If we can't dereference them, then what would be the use of such a call ?
> Can you cite a example for the above scenario ?

They can be dereferenced in a context where the structure isn't
anonymous.

A library can define a structure in a private header which is used by
the library's source files, while the public header only has an
anonymous declaration. The library can pass pointers to the
application, which can pass them back to the library, but the
application can't access the structure's members. To the application,
the pointer is an opaque handle.

E.g.:

private header:

	struct foo { int x; };

library source:

	#include "foo_priv.h"
	struct foo *foo_new(void)
	{
		struct foo *p = malloc(sizeof(struct foo));
		p->x = 0;
		return p;
	}
	void foo_set(struct foo *p, int x)
	{
		p->x = x;
	}
	int foo_get(struct foo *p)
	{
		return p->x;
	}

public header:

	struct foo;

	extern struct foo *foo_new(void);
	extern void foo_set(struct foo *p, int x);
	extern int foo_get(struct foo *p);

-- 
Glynn Clements <glynn@xxxxxxxxxxxxxxxxxx>
-
: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux