Search code examples
c++structmemset

zero an array inside a struct in c++


I have a struct defined in my program.

struct A{
    int arr[10];
}

Lets say I have a pointer to it. A * a = new A;

I can zero it in two ways:

memset(&a->arr,0,sizeof(A));
memset(a->arr,0,sizeof(A));

both work and look the same!

which one is more correct?


Solution

  • This is the correct way for just the array

    memset(a->arr,0,sizeof(a->arr))
    

    Picked out the arr member just in case there are other structure members that do not need to be touched. Makes no difference in your example the following will do likewise

    memset(a->arr,0,sizeof(A));