Click here to Skip to main content
13,092,725 members (73,351 online)
Rate this:
Please Sign up or sign in to vote.
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: bad
Please Sign up or sign in to vote.

Solution 3

Use the function named memset.
memset(array, value, len)
Rate this: bad
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:[^].

Rate this: bad
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;

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.170813.1 | Last Updated 7 Nov 2012
Copyright © CodeProject, 1999-2017
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