Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ array with variable no. of elements?

  1. Apr 6, 2012 #1
    Code (Text):

    #include <iostream>
    using namespace std;

    int a;

    int main()
    {
        cin >> a;
        int c [a];
        for (int i = 1;i!=a+1;i++)
        {
            c [i] = i;
            }
        for (int i = 1;i!=a+1;i++)
        {
            cout << c [i] << endl;
            }
        return 0;
        }
     
    This compiles and does exactly what it's supposed to. But wait, I thought you could only declare arrays with a constant number of elements?
     
  2. jcsd
  3. Apr 6, 2012 #2
    Aren't you declaring an array of length "a", where "a" has been initialized via input? (I'm not a C++ programmer, so I don't know if this is what you're asking about).
     
  4. Apr 6, 2012 #3

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    That feature is part of C99. Some compilers will also allow you to use this feature in C++.

    However, I highly doubt this feature made it into C++11, since it would play havoc with C++'s type system.


    P.S. why is a global? :grumpy:


    P.P.S. your program has undefined behavior. In C/C++, arrays use 0-up indexing, so a 10-long array has indices 0 through 9. You are attempting to read/write to array index 10, which permits Bad Things to happen.
     
  5. Apr 6, 2012 #4
    Sorry, a being global was a so-called "vestigial organ." Dunno, it seemed to work fine, but I took your advice and rewrote it to go 0 - a-1 instead of 1 - a. This also worked fine.
     
  6. Apr 6, 2012 #5

    jtbell

    User Avatar

    Staff: Mentor

    The standard way to get the effect of a variable-length array in C++ is to use a vector. Adapting your example and fixing the indexing bounds:

    Code (Text):

    #include <iostream>
    #include <vector>

    using namespace std;

    int main()
    {
        int a;
        cout << "Enter the size of the vector: ";
        cin >> a;
        vector<int> c(a);
        for (int i = 0; i < a; i++)
        {
            c[i] = i;
        }
        for (int i = 0; i < a; i++)
        {
            cout << "c[" << i << "] = " << c[i] << endl;
        }
        return 0;
    }
     
     
  7. Apr 6, 2012 #6

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You're right. This concept is not a part of C++, past, present, or future. There's no reason for it; std::vector works quite nicely.
     
  8. Apr 6, 2012 #7
    Yep use a vector, easy peasy.

    You could also dynamically allocate more/less memory for an array - forgive my lack of C++ experience but in C you could use malloc()/realloc().
     
  9. Apr 7, 2012 #8
    you can dynamically allocate an array from a pointer like this:

    Code (Text):

    int *a;
    a = new int [1024];  //allocate
    delete [] a;             //deallocate
     
    or even,

    Code (Text):

    int **a;
    a=new int * [1024];
    for ( int i=0; i < 1024; ++i)
        a= new int [1024];

    for (int i=0; i < 1024; ++i)
       delete [] a;
    delete [] *a;
     
    But, vectors are favorable to dynamic arrays in c++ according to all of the advice I have received.

    Code (Text):

    #include <vector>

    vectory <int> x;

    for (int i=0;  i < 1024; ++i)
        x.push_back(0);              //create a vector of 1024 items each equal to zero.

    x[100]=24;                        //set value for one of the items in the vector

    for (int i=0; i<1024; ++i)
       x.pop_back();                  //remove all of the items in the vector

     
     
  10. Apr 7, 2012 #9

    jtbell

    User Avatar

    Staff: Mentor

    It's quicker to do it this way:

    Code (Text):

    vector<int> x(1024, 0);
     
    Where push_back() really shines is when you're reading data and don't know in advance how much there will be:

    Code (Text):

    vector<int> x;  // zero size initially

    int num;
    cout << "Gimme some numbers, terminate with ^D: ";
    while (cin << num)
    {
        x.push_back(num);  // x "grows" as necessary to accommodate the input
    }

    cout << "You entered: ";
    for (int k = 0; k < x.size(); k++)
    {
        cout << x[k] << " ";
    }
    cout << endl;
     
    Or if you have a compiler that supports C++11:

    Code (Text):

    cout << "You entered: ";
    for (int xnum : x)  // "ranged for-loop"
    {
        cout << xnum << " ";
    }
    cout << endl;
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ array with variable no. of elements?
  1. Arrays in C++ (Replies: 10)

  2. Arrays c++ (Replies: 14)

  3. C++ Array (Replies: 10)

  4. C# arrays (Replies: 1)

Loading...