Initializing arrays to zero all in one go?

This is a discussion on Initializing arrays to zero all in one go? within the C++ Programming forums, part of the General Programming Boards category; Hello, Is there a way to initialize a 2D or 1D array to zeros all at the same time? I ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Location
    London
    Posts
    41

    Initializing arrays to zero all in one go?

    Hello,

    Is there a way to initialize a 2D or 1D array to zeros all at the same time?

    I have this:

    Code:
    double inputs[50][2];
    double desiredOutputs[50];
    int iterate = 0;
    while(getline(file,line))
    {
         // code
          inputs[iterate][0] = x_1D;
          inputs[iterate][1] = c_1D;
    
          desiredOutputs[iterate] = y_1D;
    
          iterate++;
    }
    However initially the arrays hold random numbers. I would like to set all of them to zero to keep the good practice of initializing everything before assigning.

    Thank you,

  2. #2
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    You could use memset().

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    681
    I don't find it a good practice to initialize everything before assigning. It just does not make sense. It slows down the program execution and makes the compiler give warnings about assigned values which are never used.

    Nearly every modern compiler has an option to inform you, if a variable is used uninitialized (some languages even require it).

    You'd better take care about your buffer overflow. I'd use a vector instead of a raw array.
    Last edited by kmdv; 09-19-2010 at 07:39 AM.

  4. #4
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    Quote Originally Posted by kmdv View Post
    I don't find it a good practice to initialize everything before assigning. It just does not make sense. It slows down the program execution and makes the compiler give warnings about assigned values which are never used.

    Nearly every modern compiler has an option to inform you, if a variable is used uninitialized (some languages even require it).

    You'd better take care about your buffer overflow. I'd use a vector instead of a raw array.
    I agree with you, and that's why I always compile my code with the maximum warning degree, as well as with fatal warnings.

    However, Kat007 asked for a way to do it. Another alternative would be using brace-initialization:

    Code:
    int my1Darray[x] = {0};
    int my2Darray[x][y] = {{0}};
    int my3Darray[x][y][z] = {{{0}}};
    In fact, I believe that this is the *correct* way to do it.

    EDIT: No it isn't. This is wrong, as it only initializes the first element (see kmdv's post). Sorry.
    Last edited by Jorl17; 09-19-2010 at 08:05 AM.

  5. #5
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    681
    Code:
    int my1Darray[x] = {0};
    int my2Darray[x][y] = {{0}};
    int my3Darray[x][y][z] = {{{0}}};
    With this code you will initialize only the first element.
    memset would be a better choice.

  6. #6
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    Quote Originally Posted by kmdv View Post
    Code:
    int my1Darray[x] = {0};
    int my2Darray[x][y] = {{0}};
    int my3Darray[x][y][z] = {{{0}}};
    With this code you will initialize only the first element.
    memset would be a better choice.

    I just checked it and you are absolutely right. I am terribly sorry for inducing other people in error.

    Although I really thought that the compiler standardly assumed that since only one element was given, the same value applied to the rest. I see now that I was wrong (a simple test case will check it). Once again, I'm sorry. There really should be an operator to initialize all the elements of an array. Maybe a syntax like: int array[x]={[]=0};.

  7. #7
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,856
    Quote Originally Posted by kmdv View Post
    I don't find it a good practice to initialize everything before assigning. It just does not make sense. It slows down the program execution and makes the compiler give warnings about assigned values which are never used.
    I totally disagree. It stops a host of errors.

    It has not slown down program execution to any measurable degree in any application I have written.
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  8. #8
    Registered User
    Join Date
    Sep 2010
    Location
    London
    Posts
    41
    Quote Originally Posted by kmdv View Post
    You'd better take care about your buffer overflow. I'd use a vector instead of a raw array.
    Thank you for your comments. Could you please explain how to 'take care of the buffer overflow'? And why? I've not had to deal with arrays a lot before.

    Thank you.

  9. #9
    Registered User
    Join Date
    Sep 2010
    Location
    London
    Posts
    41
    Quote Originally Posted by novacain View Post
    I totally disagree. It stops a host of errors.

    It has not slown down program execution to any measurable degree in any application I have written.
    Interesting to see different comments. I am aware that compiler will warn about variables initialised and 'not used', however just something I was taught is to always set to 0 first.

    OK I think what I saw is that there is no easy way to initialize all array elements to zero, so I will for now go with just declaring it and then assigning numbers I want to each element.

    Thank you again for your comments.

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    > With this code you will initialize only the first element.
    Erm, nope.

    Code:
    int my1Darray[x] = {0};  // first element 0, remainder zero
    int my1Darray[x] = {1,2,3};  // first elements 1,2,3, remainder zero
    The C99 Draft (N869, 18 January, 1999) - point #21
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    There is not golden rule when it comes to initializing. It would have a significant measurable impact if you initialize a big array that it is used in heavy computations.

    You can make some more specific rules for your programming tactics. Like
    -Initialize arrays that are used for user input
    -Initialize arrays that are not used in heavy computations
    -Initialize arrays where the initial value will be the default value

    If you are just creating an array, I would say leave it unitialized. If you feel that at one point you want to have a check so that a valid value is given, add the initializing code then.

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    C++ even allows for leaving out the 0:
    Code:
    T myarray[x] = {};
    Also, re buffer overruns: SourceForge.net: Buffer overrun - cpwiki
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    Quote Originally Posted by Salem View Post
    > With this code you will initialize only the first element.
    Erm, nope.

    Code:
    int my1Darray[x] = {0};  // first element 0, remainder zero
    int my1Darray[x] = {1,2,3};  // first elements 1,2,3, remainder zero
    The C99 Draft (N869, 18 January, 1999) - point #21
    Aah! So I was right after all! Except that I thought that {1} would set all to 1, which is false.

    Just in case some people don't want to follow the link, here's the relevant part:

    #21
    If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
    @Kat007

    Using memset is fairly easy:

    Code:
    int myCrazyArray[5][10][22][99];
    memset(myCrazyArray, 0, sizeof(myCrazyArray));
    Just remember that initializing to, say, 1, isn't as simple. This sets every byte to 0. If you use 1, then every byte will be one. Since an int is (usually) 4 bytes, you'd get the integer whose 4 bytes were set to 1, which is something you probably didn't want.

  14. #14
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    memset is dangerous and should be avoided in C++. Recommend you use std::fill instead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    Quote Originally Posted by Elysia View Post
    memset is dangerous and should be avoided in C++. Recommend you use std::fill instead.
    I had never investigated in that area, but I just googled it and I understand why, thanks. I agree, avoid using memset in C++. The problem is only with non-POD types, right?

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 23
    Last Post: 12-06-2008, 12:39 PM
  2. initializing multi-dimensional arrays
    By cyberfish in forum C++ Programming
    Replies: 4
    Last Post: 10-31-2007, 08:15 PM
  3. newbee: initializing arrays
    By breaka in forum C Programming
    Replies: 11
    Last Post: 06-12-2006, 12:20 PM
  4. Initializing dynamic arrays
    By cunnus88 in forum C++ Programming
    Replies: 9
    Last Post: 11-21-2005, 08:50 AM
  5. Replies: 14
    Last Post: 03-17-2003, 09:07 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21