C++ array with variable no. of elements?

In summary, the programmer attempted to use a variable-length array in C++, but found that it has undefined behavior. A better option is to use a vector. Another option is to dynamically allocate memory for the array.
  • #1
Whovian
652
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
  • #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).
 
  • #3
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? :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.
 
  • #4
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? :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.

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.
 
  • #5
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;
}
 
  • #6
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.
 
  • #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().
 
  • #8
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
 
  • #9
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;
 

What is a C++ array with variable number of elements?

A C++ array with variable number of elements, also known as a dynamic array, is a data structure that allows for a flexible number of elements to be stored in a single array. Unlike a traditional array, where the size is fixed at compile time, a dynamic array can be resized at runtime as needed.

How do you declare a C++ array with variable number of elements?

To declare a C++ array with variable number of elements, you can use the "new" keyword followed by the data type and the number of elements you want to allocate. For example, "int *arr = new int[10];" will create a dynamic array of integers with 10 elements.

How do you add elements to a C++ array with variable number of elements?

To add elements to a C++ array with variable number of elements, you can use the "push_back()" function if you are using the Standard Template Library (STL). If not, you can create a new array with a larger size and copy the contents of the original array, along with the new element, into the new array.

How do you access elements in a C++ array with variable number of elements?

To access elements in a C++ array with variable number of elements, you can use the index notation (e.g. arr[0], arr[1], etc.) just like with a traditional array. However, it is important to check the size of the array before accessing elements to avoid errors.

How do you delete a C++ array with variable number of elements?

To delete a C++ array with variable number of elements, you can use the "delete[]" keyword followed by the name of the array. This will free up the memory allocated for the array. It is important to delete dynamic arrays when they are no longer needed to prevent memory leaks.

Similar threads

  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
15
Views
2K
  • Programming and Computer Science
Replies
3
Views
726
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
5
Views
4K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
13
Views
1K
  • Programming and Computer Science
Replies
6
Views
8K
Back
Top