coding style - C conventions - how to use memset on array field of a struct -


i wold settle argument proper usage of memset when zeroing array field in struct (language c).

let have following struct:

  struct my_struct {         int a[10]     } 

which of following implementations more correct ?

option 1:

void f (struct my_struct * ptr) {     memset(&ptr->a, 0, sizeof(p->a)); } 

option 2:

void f (struct my_struct * ptr) {         memset(ptr->a, 0, sizeof(p->a)); } 

notes:

if field of primitive type or another struct (such 'int') option 2 not work, , if pointer (int *) option 1 not work.

please advise,

for non-compound type, not use memset @ all, because direct assignment easier , potentially faster. allow compiler optimizations function call not.

for arrays, variant 2 works, because array implictily converted pointer most operations.

for pointers, note in variant 2 value of pointer used, not pointer itself, while array, pointer to array used.

variant 1 yields address of object itself. pointer, of pointer (if "works" depends on intention), array, of array - happens address of first element - type differs here (irrelevant, memset takes void * , internally converts char *).

so: depends; array, not see difference actually, except address-operator might confuse reads not familar operator preceedence (and more type). personal opinion: prefer simpler syntax, not complain other.

note memset other value 0 not make sense actually; might not guarantee array of pointers interpreted null pointer.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -