Re: hiding structure members
- From: Tydr Schnubbis <fake@xxxxxxxxxxxx>
- Date: Mon, 27 Jun 2005 11:28:36 GMT
Madhav wrote:
You can't use malloc without knowing the size of the struct. Let's say you have a this in you .h file:Hi all, I was going through a piece of code which had a very interesting format. There were two files: one was a .h file, and the other was a .c file. The .c file had a structure defined in it which was typedef'ed in .h file.
what I observered was even more interesting: I was allowed to declare objects of structure that was typedefed in the header file, but I could not use any of the members of the structure outside the .c file which delcared it. Every time I did that, I got error: "dereferencing pointer to incomplete type".
Why is it so that I was not allowed to access the members but I was allowed to use structure definition in calls to malloc()? does this problem exists because the structure definition was not available in the header file? Or is this a neat trick to hide the structure members?
typedef struct my_struct my_struct_t;
And you do this in a .c file:
malloc(sizeof(my_struct_t));
which wouldn't compile. sizeof needs the definition to work. So what you're saying can't happen. You probably have the definition in scope without knowing it. Or the typedef is a pointer, like 'typedef struct my_struct *my_struct_p', in which case you'd be malloc'ing memory only for a pointer, not for the struct itself.
But this trick could indeed be used to allow you to use a struct without knowing it's definition (members, fields). But you could only use it through pointers, and wouldn't be able to allocate new instances yourself.
.
- References:
- hiding structure members
- From: Madhav
- hiding structure members
- Prev by Date: Standard way of dealing with directories
- Next by Date: Re: Origin of size_t? Curious.
- Previous by thread: Re: hiding structure members
- Next by thread: Re: read 32 bit value into 64 bit variable?
- Index(es):
Relevant Pages
|