lundi 29 juin 2015

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,


Aucun commentaire:

Enregistrer un commentaire