Thread: c++ specify the starting values of an array?

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    4

    c++ specify the starting values of an array?

    How can you specify the starting values of an array?

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    Do you mean how do you declare and initialize the values of an array? If so, try something like
    Code:
    int foo[5] = {1,2,3,4,5};
    // or without the size explicitly, like:
    int bar[] = {1,2,3,4,5};
    Do a similar thing for any other type: type a list of values, separated by commas, and the entire list is surrounded by curly brackets.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Code:
    int nums[1000] = {0};  // All elements are initialized to 0.
    int nums[1000] = {1, 2, 3};  // First 3 elements are initialized to 1, 2, & 3, the rest are initialized to 0.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    Quote Originally Posted by cpjust View Post
    Code:
    int nums[1000] = {0};  // All elements are initialized to 0.
    I just wanted to point out that all the elements are initialized to zero, but not because you did "{0}". You would get the same array if you did "{}". Specifying the values of the array when you declare it allows you to specify some (may be all) values of the array, and all other values are set to 0 (at least for our example). The above notation may be misleading, and someone might do
    Code:
    int nums[1000] = {5};
    thinking it would initialize all elements to "5", when it just sets the first element to 5 and all others to 0.

    Let me know if Im incorrect and misunderstanding things. I know I thought that specifying one value initialized the whole array to that value was true in Java--it might actually be, but Ive never verified or looked it up.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2008, 10:25 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Storing values from Edit Box into an array
    By E_I_S in forum C++ Programming
    Replies: 10
    Last Post: 06-05-2008, 06:24 AM
  4. 3-d array assign string values
    By WaterNut in forum C++ Programming
    Replies: 8
    Last Post: 07-01-2004, 12:02 AM
  5. eliminating dup values in array
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 04-19-2002, 06:05 PM