Hi Doug,

you should consult a C-book first, you will definitely find it.

Its the first one. Look:

struct foo *bar[10];

So 'bar' is an array of 10 pointers to 'struct foo'.
sizeof(bar) will give you 40 on an 32-bit machine, 
and 80 on an 64-bit machine (assuming that a pointer 
on an 32-machine is 4 bytes, and on an 64-bit machine 
its 8 bytes).

memset(bar, 0, sizeof(*bar));

If you use the name of an array
in an expression, the compiler will automatically 
convert it into a pointer (to the first element).
So 'bar' is now a pointer, and *bar will give you
the size of a pointer to 'struct foo' (which
is the first element and which will be 4 or 8 bytes).

But keep in mind that 'sizeof' is a compile-time operator.
If you have a pointer like

what-ever-type *foo;

then 

sizeof(*foo);

will always give you the size of 'what-ever-type'.

That means that 

sizeof(**bar);

will give you the size of 'struct foo'.

A last comment: better not use 'memset' here.
The reason is that a NULL-pointer isn't something
which has a 0-bytes-pattern in memory. Its only
the case that most C-implementations do it that way. 
But a C-implementation is free to use whatever it likes
to represent a NULL-pointer internally.

So while 'memset' will work on some platforms 
(and compilers), on other platforms you will have
unintialized pointers, and not NULL-pointers. 

Hope this helps.


On Thu, Nov 10, 2011 at 10:39:29AM +0800, Doug Brewer wrote:
> Hello,
> 
> I have the following lines in C:
> 
> struct foo *bar[10];
> 
> If I want to clear out that structure, should I use
> 
> memset(bar, 0, sizeof(bar));
> or
> memset(bar, 0, sizeof(*bar));
> 
> Thank you.

Reply via email to