Is there a better way to initialize a selected array in C ++?

How to write this in a different (possibly shorter) way? Is there a better way to initialize a selected array in C ++?

int main(void) { int* a; a = new int[10]; for (int i=0; i < 10; ++i) a[i] = 0; } 
+6
c ++ arrays pointers initialization
source share
10 answers
  int *a =new int[10](); // Value initialization 

ISO C++ Section 8.5/5

To initialize an object of type type T means:

- if T is a class type (section 9) with a constructor declared by the user (12.1), then the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);

- if T is the type of a non-unit class without a constructor declared by the user, then each non-static data element and components of the base class T are initialized with a value;

- if T is an array type, then each element is initialized with a value;

- , otherwise the object is initialized to zero

For differences between the terms zero initialization , value initialization and default initialization , read this

+37
source share
 std::vector<int> vec(10, 0); int *a = &vec.front(); 
+22
source share

You can use memset

Sets the first num bytes of the memory block pointed to by ptr to the specified value (interpreted as unsigned char).

+20
source share

What about the three ways?

 1. int *a = new int[10](); 2. std::vector<int> a(10, 0); 3. int *a = new int[10]; memset(a, 0, sizeof(int) * 10); 

Due to popular demand, a couple more:

 4. int *a = new int[10]; std::fill(a, a + 10, 0); 5. std::vector<int> a(10); std::fill(a.begin(), a.end(), 0); 
+17
source share
 int main(void) { int *a; a = new int[10]; for(int i=0;i<10;++i) a[i]=0; } 

; -)

+4
source share
 #include <algorithm> int main() { int *a = new int[10]; std::fill(a, a + 10, 0); } 
+2
source share
 int *a = (int*) calloc(10, sizeof(*a)); 

(and check if it is NULL, or rewrite the safe shell against calloc).

+2
source share

Perhaps you could try something like this:

 int* initIntArray(int size) { int *temp = new int[size]; for(int i = 0; i < size; i++) { temp[i]=0; } return temp; } int main () { int* a = initIntArray(10); int* b = initIntArray(10); int* c = initIntArray(10); //do stuff with arrays delete [] a; delete [] b; delete [] c; return 0; } 
+1
source share

I'm C guy and not too sure what the β€œnew” really does, but can it work?

 int main( void ) { int i = 10; // start at the far end of the array int *a = new int[10]; while ( i-- ) a[i] = 0; // while ( i == 9, 8, 7, ... , 0 ) } 

Just to show my new counter loop lover: while (condition).

0
source share

By the way, what about using calloc ()? they say

int i*=(int[10])calloc(10*sizeof(int))

Well, I'm just another C guy .. any comment is welcome here

0
source share

All Articles