Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
how to set initialize same value to all value in this statment
int *Array = new int[X];
Posted 6-Nov-12 9:32am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Use the function named memset.
memset(array, value, len)
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

There is not such thing in the language itself (why having it, it you can always do it by yourself? so the language feature would be redundant). So, you just need to write a loop and initialize all the elements in code.
 
Basically, whatever you do, this is what will always happen under the hood. You can use std::fill from <algorithm>:
#include <algorithm>

//...

const int X = //... // array size
const int someValue = //...
int Array[X]; // or allocate it on heap as you already did
std::fill(Array, Array + X, someValue); // this is not obvious,
//but it will create iterators from your arrays
// and pass then to the function
 
Please see: http://www.cplusplus.com/reference/algorithm/fill/[^].
 
—SA
  Permalink  
v5
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

In addition to the solution by SAK, you can initialize a statically defined array like that:
int A[10] = {1,1,1,1,1,1,1,1,1,1};
This code initializes the elements of the array with the constants provided in the list. This list may not have more elements than the array, but it may be shorter:
int A[10] = {1,1,1};
This code initializes the array with the values {1,1,1,0,0,0,0,0,0,0}. Note that the elements that you don't explicitely assign will be automatically intialized with 0.
 
If your purpose is to intialize the entire array with 0, you can do this like that:
int A[10] = {0};
 
Note that this kind of intialization only works with static arrays, not dynamically allocated ones. However, the containers in the Standard Template Library (STL) provide various constructors that let you do just that. You could for instance use std::vector to create a vector of 10 elements that are initialized to 7:
#include <vector>
int main() {
   std::vector<int> A(10, 7);
   // do some stuff ...
   return 0;
}
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 420
1 OriginalGriff 344
2 Peter Leow 200
3 John C Rayan 126
4 CHill60 90
0 Sergey Alexandrovich Kryukov 7,393
1 OriginalGriff 5,711
2 Peter Leow 4,157
3 CHill60 2,858
4 Mika Wendelius 2,850


Advertise | Privacy | Mobile
Web02 | 2.8.150224.1 | Last Updated 7 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100