Thread: Dynamic Array Size?

  1. #1
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434

    Dynamic Array Size?

    Is it possible to have a dynamic array size?

    For example:
    Code:
    ...
    int size;
    cout<<"size: ";
    cin>>size;
    cin.ignore();
    int array[size];
    ...
    It wont compile but i was wondering if it's possible to achieve that some way.


    Thanks!
    "Anyone can aspire to greatness if they try hard enough."
    - Me

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    A std::vector?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434
    Oh... ha.

    Never used a vector before.

    I'll have to look into that i suppose


    Thanks!
    "Anyone can aspire to greatness if they try hard enough."
    - Me

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    If you want to have the user input a value that will serve to initialize the array only once, you can dynamically allocate memory using the new operator. If you want to change the array's size you want an std::vector or an std::list.

    Code:
    int* array = new array[size]
    
    // ...
    
    // not to forget !
    delete[] array;
    array = 0;

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Even if you don't need to change the array size, it is generally better to use a vector or other container in C++.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. size of dynamic array
    By tommy_gunn in forum C Programming
    Replies: 3
    Last Post: 12-30-2004, 08:01 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM