2

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?

rafi wiener
  • 587
  • 1
  • 9
  • 19
  • i know i can use a class and a constructor, this code snippet is an small demo that demonstrate an example so using a class or a different function instead of memset will not help – rafi wiener Jun 29 '15 at 15:31
  • @DeepBlackDwarf I disagree with the duplicate. – o11c Jun 30 '15 at 03:22

5 Answers5

2

which one is more correct?

I'd argue neither. The easiest way would be to value initialize the allocated object:

A * a = new A();

Of course, this assumes that you actually have a good reason to new this object.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

Since you are using C++ I would take advantage of C++11 features and use:

#include <iostream>
#include <cmath>
using namespace std;

struct A{
    int arr[10]{};  // initializes array with all 0's
};

int main() {
    A * a = new A;
    for (auto e : a->arr) // ranged based for loop to show all of the 0's
        cout << e << "\n";
    return 0;
}

You can see it running with this Live Example

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

While the type of each expression is different, the actual result, the pointer you pass to memset, will be equal in both cases.

Personally I would probably use std::fill instead of memset in a C++ program:

std::fill(std::begin(a->arr), std::end(a->arr), 0);

Also note that if you have more members in the structure, sizeof(A) will be different from sizeof(a->arr) (or sizeof(A::arr)).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

you can define a default construct function

struct A{
    int arr[10];
    A():arr(){}
};
kiviak
  • 1,083
  • 9
  • 10
0

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));
dubnde
  • 4,359
  • 9
  • 43
  • 63