Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wold like to settle an argument about proper usage of memset when zeroing an array field in a struct (language is C).

Let say that we have the following struct:

  struct my_struct {
        int a[10]
    }

Which of the following implementations are 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 the field was of a primitive type or another struct (such as 'int') option 2 would not work, and if it was a pointer (int *) option 1 would not work.

Please advise,

like image 780
dk7 Avatar asked Jan 23 '26 11:01

dk7


1 Answers

For a non-compound type, you would not use memset at all, because direct assignment would be easier and potentially faster. It would also allow for compiler optimizations a function call does not.

For arrays, variant 2 works, because an array is implictily converted to a pointer for most operations.

For pointers, note that in variant 2 the value of the pointer is used, not the pointer itself, while for an array, a pointer to the array is used.

Variant 1 yields the address of the object itself. For a pointer, that is that of the pointer (if this "works" depends on your intention), for an array, it is that of the array - which happens to always be the address of its first element - but the type differs here (irrelevant, as memset takes void * and internally converts to char *).

So: it depends; for an array, I do not see much difference actually, except the address-operator might confuse reads not so familar with operator preceedence (and it is more to type). As a personal opinion: I prefer the simpler syntax, but would not complain about the other.

Note that memset with any other value than 0 does not make much sense actually; it might not even guarantee an array of pointers to be interpreted as null pointer.

like image 51
too honest for this site Avatar answered Jan 25 '26 03:01

too honest for this site



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!