Re: memset doubt



"srivatsan_b" <srivatsanbs@xxxxxxxxx> writes:
> Can somebody explain whether an explicit typecast is mandatory while
> calling memset function for a structure? like in the following code
> snapshot.....
> struct some_structure x;
> memset((some_structure*)&x,0,sizeof(some_structure));
> Will memset(&x,0,sizeof(some_structure)); cause some issues?

Assuming that you've remembered to #include <string.h>, which declares
the memset() function, the cast is unnecessary. Any object pointer
type can be implicitly converted to void*, and vice versa.

There are a couple of problems with your code, one serious and one
cosmetic.

Given a declaration of "struct some_structure", there is no type
called "some_structure"; the struct keyword is necessary unless you've
also declared it as a typedef. (Some would argue that typedefs for
struct types are poor style.)

<OT>
Note that the rules are different for C++. If I recall correctly, a
declaration of "struct some_structure" makes "some_structure" visible
as a type name, and there is no implicit conversion to void*. That
shouldn't be relevant unless you're using a C++ compiler -- and if you
are, you're in the wrong newsgroup.
</OT>

Also, using the size of the object makes for cleaner code than using
the size of the type. For example:

struct some_structure x;
memset(&x, 0, sizeof x);

Not only is this shorter, it avoid errors if the type of x is changed.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: incorrect warning?
    ... typedef struct Foo Foo; ... while you can only have the typedef line once. ... if zog.h declares a prototype for a function ... zog() that operates on a "Zog", ...
    (comp.lang.c)
  • Re: Type alias in C#
    ... Not all value types are structures, for example, enum. ... Lutz Roeder's refector declares Enum as a 'public ... here is that the term "struct" and "value type" are being passed around as synonomous -- which they really aren't. ... An enum is a class that derives from System.Enum. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: accessing base class member data .. more
    ... But this only declares the variable. ... > Consider the struct. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: forward declaration
    ... char * first; ... The unqualified phrase "a struct" can be ambiguous; ... that declares an object of type "struct person". ... typedef struct person person; ...
    (comp.lang.c)
  • Re: mutually referential (Pg 140 K&R2)
    ... >> struct s *p declares p using an incomplete struct s type, ... You can't forward declare an enum ...
    (comp.lang.c)