12,505,405 members (64,258 online)
Rate this:
See more:
how to set initialize same value to all value in this statment
int *Array = new int[X];
Posted 6-Nov-12 8:32am

Rate this:

## Solution 3

Use the function named memset.
memset(array, value, len)
v2
Rate this:

## 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```

—SA
v5
Rate this:

## 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;
}```

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

Top Experts
Last 24hrsThis month
 OriginalGriff 263 Karthik Bangalore 235 Maciej Los 228 David_Wimbley 220 ppolymorphe 191
 OriginalGriff 7,266 ppolymorphe 3,984 Maciej Los 3,731 David_Wimbley 3,012 Karthik Bangalore 3,001

Advertise | Privacy | Mobile
Web02 | 2.8.160927.1 | Last Updated 7 Nov 2012