• C

memset: need & operator for strings?

If I am using memset() to set a string to nulls
(in particular a string within a structure)

typedef struct
    long id_code;
    char last_name[31];
    char first_name[21];
    /* etc */

I always forget if I need the address (&) operator.
In other words,
which of the following to statements is preferred:

memset(person.last_name, 0, sizeof(person.last_name));
memset(&person.last_name, 0, sizeof(person.last_name));

My gut feeling is that it does not matter for a string
but would appreciate any feedback.

Stephen KairysTechnical Writer - ConsultantAsked:
Who is Participating?
Kent OlsenData Warehouse Architect / DBACommented:
Hi stevefromc,

No matter whether the object is in a union, struct, globals block, stack, or anywhere else, the rule is simple.  If the object is defined as an array or a pointer, it is a pointer and the '&' symbol isn't needed.  If the object is a scalar variable, then the '&' is needed.

Good Luck!
memset(person.last_name, 0, sizeof(person.last_name));

This is right version. In C string is pointer: last_name points to first bytes of memory region. Non-pointer types require &.
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Thanks to both of you. Accepted answer goes to Kent as per his more detailed response.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.