Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 132,387 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,217 people online right now. Registration is fast and FREE... Join Now!




Initializing to zero in pointers

 
Reply to this topicStart new topic

Initializing to zero in pointers

prads
post 29 Aug, 2008 - 03:43 PM
Post #1


D.I.C Head

**
Joined: 22 Oct, 2007
Posts: 111


My Contributions


Hello,
I have a dynamically memory allocated variable pointer which has to be initialized to zero.
CODE

double *var = new double[6];
    var[0] = 0;
    var[1] = 0;
    var[2] = 0;
    var[3] = 0;
    var[4] = 0;
    var[5] = 0;


Is there a simpler one-line way of writing this? something like this...??
CODE

double *var = new double[6]= {0};


Because it gets tedious when I need more than 6 memory allocation?
Thanks,
prads
User is offlineProfile CardPM

Go to the top of the page

perfectly.insane
post 29 Aug, 2008 - 03:53 PM
Post #2


D.I.C Addict

Group Icon
Joined: 22 Mar, 2008
Posts: 557



Thanked 46 times

Dream Kudos: 25

Expert In: C/C++

My Contributions


There's memset.

memset(var, 0, 6 * sizeof(double));

There's std::fill:

std::fill(var, var + 6, 0.0);

Which is actually typesafe.

There's a for loop:
for(int x = 0; x < 6; x++) var[x] = 0.0;

That's a one liner, right?

User is offlineProfile CardPM

Go to the top of the page

prads
post 30 Aug, 2008 - 09:27 PM
Post #3


D.I.C Head

**
Joined: 22 Oct, 2007
Posts: 111


My Contributions


Yes. thanks, rolleyes.gif
prads icon_up.gif biggrin.gif
User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 11/22/08 06:56AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month