6

How to write this in another (perhaps shorter) way? Is there a better way to initialize an allocated array in C++?

int main(void) {
   int* a;
   a = new int[10];
   for (int i=0; i < 10; ++i) a[i] = 0;
}
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • I'm voting to close this because this question is incredibly vague. There are an infinite number of programs that fit the stated criteria. What's your specific problem here? – Omnifarious Jul 14 '10 at 13:28

10 Answers10

39
 int *a =new int[10](); // Value initialization

ISO C++ Section 8.5/5

To value-initialize an object of type T means:

— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;

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

otherwise, the object is zero-initialized

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

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 3
    This *is* better because it deals well with arrays of objects and in a template context. But bear in mind that for the simple example given above the generated code is likely to be very similar (perhaps identical). – dmckee --- ex-moderator kitten Jul 15 '10 at 19:55
22

How about 3 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);
Justin Ardini
  • 9,768
  • 2
  • 39
  • 46
20
std::vector<int> vec(10, 0); 
int *a = &vec.front();
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • 1
    And the 0 isn't even required, since `int()` is the default value. –  Jul 16 '10 at 04:58
18

You could use memset

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

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • 5
    Old, I know, but there's really no reason to use `memset`. `std::fill` is a more generic way of getting the same thing (which means the code can be consistent) at no loss. – GManNickG Jul 19 '10 at 20:56
  • Since `memset` changes by _bytes_, it cannot be used for non-zero values. http://stackoverflow.com/a/17288891/2680660 – Efreeto Feb 08 '17 at 07:20
4
int main(void) { int *a; a = new int[10]; for(int i=0;i<10;++i) a[i]=0; }

;-)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
nob
  • 1,404
  • 10
  • 13
3
int *a = (int*) calloc(10, sizeof(*a));

(and check if is NULL, or rewrite a safe wrapper against calloc).

Andrei Ciobanu
  • 12,500
  • 24
  • 85
  • 118
2
#include <algorithm>

int main() {
    int *a = new int[10];
    std::fill(a, a + 10, 0);
}
Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
1

Maybe 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;
}
jmont
  • 423
  • 3
  • 12
  • is there a reason someone voted down this answer?? i'd like to what I did wrong (seriously!! no sarcasm here) – jmont Jul 14 '10 at 21:11
  • Your answer seems fine. I don't understand the downvotes either. – Aaron McDaid Jul 14 '10 at 22:58
  • 1
    This is just bad advice; it's nearly an exact copy of std::fill_n with downsides but no benefit. –  Jul 16 '10 at 05:04
  • I didn't down-vote, but I think the problem some may have had is that this doesn't deviate much from the OP's original problem. I think the OP is trying to eliminate writing a for-loop to do the initialization. – Steve Guidi Jul 25 '10 at 05:07
0

by the way, what about using calloc()? say

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

well i'm just another C guy.. any comment is welcomed here

Jokester
  • 5,501
  • 3
  • 31
  • 39
-1

I'm a C guy and not too sure what "new" really does, but could this 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 off my new loop-counter favorite: while(condition).

Pete Wilson
  • 8,610
  • 6
  • 39
  • 51
  • 1
    1) why is `i` static? 2) Why `while` instead of the established, idiomatic `for`? – Konrad Rudolph Jul 14 '10 at 14:27
  • Where is the calloc :P, if you are a C guy ? – Andrei Ciobanu Jul 14 '10 at 14:28
  • @Konrad: `static` is zero initialized; and `while` is different from `for`. I agree with you, though: outside the scope of this question, I'd be upset with someone who presented the code shown as a good way of doing things. – Jonathan Leffler Jul 14 '10 at 15:02
  • @Andrei, I forgot about calloc, dang it :-) I started trying this technique about 6 mmonths ago; it's beginning to seem cleaner and more obvious. Tons of off-by-one mistakes in the beginning. A somewhat more obscure version:
    
        int i = 10;
        int *a = new int[10];
        while ( i-- ) a[i] = 0;
    – Pete Wilson Jul 14 '10 at 18:00