C/C++ C++ array with variable no. of elements?

AI Thread Summary
C++ does not support variable-length arrays as a standard feature, unlike C99, and using them can lead to undefined behavior due to improper indexing. The recommended approach for dynamic arrays in C++ is to use the `std::vector` class, which manages memory automatically and allows for dynamic resizing. The discussion highlights the importance of correct indexing, as C++ arrays are zero-indexed, and suggests using vectors for better safety and functionality. Additionally, dynamic memory allocation can be achieved using pointers and `new`, but vectors are preferred for their ease of use. Overall, adopting `std::vector` is the best practice for handling arrays with variable sizes in C++.
Whovian
Messages
651
Reaction score
3
Code:
#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?
 
Technology news on Phys.org
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).
 
Whovian said:
But wait, I thought you could only declare arrays with a constant number of elements?
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? 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.
 
Hurkyl said:
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?


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.

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.
 
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:
#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;
}
 
Hurkyl said:
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.
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.
 
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().
 
you can dynamically allocate an array from a pointer like this:

Code:
int *a;
a = new int [1024];  //allocate
delete [] a;             //deallocate

or even,

Code:
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:
#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
 
jreelawg said:
Code:
vector <int> x;

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

It's quicker to do it this way:

Code:
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:
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:
cout << "You entered: ";
for (int xnum : x)  // "ranged for-loop"
{
    cout << xnum << " ";
}
cout << endl;
 
Back
Top