Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Init array with a non-zero value (http://www.programmingforums.org/showthread.php?t=15632)

kurt Apr 15th, 2008 10:55 PM

Init array with a non-zero value
 
This is embarrasing, but I've always thought:

int variable[10] = {9};

will init all items to 9. But it does not.

Any cool way to init to a non-zero value besides a for-loop?

Thanks in advance.

mbd Apr 15th, 2008 11:16 PM

Re: Init array with a non-zero value
 
:

  1. #include <algorithm>
  2.  
  3. ...
  4.  
  5. int variable[10];
  6. std::fill_n(variable, 10, 9);


still just a loop under the hood

OpenLoop Apr 16th, 2008 6:57 AM

Re: Init array with a non-zero value
 
For smaller arrays, you can do this
:

  1. int variable[5] = {9,9,9,9,9};


lectricpharaoh Apr 16th, 2008 3:48 PM

Re: Init array with a non-zero value
 
Quote:

Originally Posted by kurt
This is embarrasing, but I've always thought:

int variable[10] = {9};

will init all items to 9. But it does not.

When you initialize an array like that, it will initialize all elements you specify to the values you give, and any remaining elements will be initialized to zero (for fundamental types) or with the default constructor (for objects). If the array does not have a subscript, then the number of elements is taken from the number of values you provide:
:

  1. // all set to 9
  2. int array1[10] = {9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
  3.  
  4. // first three set to 9, rest set to 0
  5. int array2[10] = {9, 9, 9};
  6.  
  7. // five elements, all set to 9
  8. int array3[] = {9, 9, 9, 9, 9};


Klarre Apr 16th, 2008 3:51 PM

Re: Init array with a non-zero value
 
memset is a function that can be pretty handy sometimes. Even thought it may not function as expected with your "int" it is good to know about it when you are using char's.
http://www.cplusplus.com/reference/c...ng/memset.html


All times are GMT -5. The time now is 11:19 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC