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?

2
  • 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 Commented Jun 29, 2015 at 15:31
  • @DeepBlackDwarf I disagree with the duplicate. Commented Jun 30, 2015 at 3:22

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

so for C which is better?
@rafiwiener Neither one is better, and neither one is worse. The compiler will most likely generate the exact same code for both variants.
@rafiwiener No clear "better", but I prefer the first one since the second one actually converts to the first one, and therefore would make the first one more "the better way"
@rafiwiener It is a matter of opinion. I would go for the second variant.
@rafiwiener My way is better. I win :-)
|
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

Comments

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)).

Comments

1

you can define a default construct function

struct A{ int arr[10]; A():arr(){} }; 

3 Comments

There's really no need for that loop! Use value initialization: A () : arr() {}.
@ juanchopanza i dont kown new features of c++11
It is an old C++03 feature
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)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.