C++ array with variable no. of elements?

Click For Summary

Discussion Overview

The discussion revolves around the topic of declaring arrays with a variable number of elements in C++. Participants explore the concept of variable-length arrays, the use of vectors as an alternative, and the implications of array indexing in C++. The conversation includes technical explanations, code examples, and considerations of C++ standards.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant presents a code snippet that seemingly allows for an array of variable length based on user input, questioning the validity of this approach in C++.
  • Another participant points out that the array is declared with a length based on user input, which may not align with standard C++ practices.
  • Some participants note that variable-length arrays are a feature of C99 and express skepticism about their inclusion in C++11 due to potential issues with the type system.
  • A participant mentions undefined behavior due to incorrect array indexing, suggesting that arrays in C/C++ use 0-based indexing.
  • Several participants advocate for using vectors in C++ as a standard way to handle variable-length arrays, providing code examples that demonstrate this approach.
  • Dynamic memory allocation techniques using `new` and `delete` are discussed as alternatives to vectors, with some participants expressing a preference for vectors due to their advantages.
  • Participants share various methods for initializing and manipulating vectors, including using `push_back()` and initializing with a specific size and value.

Areas of Agreement / Disagreement

There is no consensus on the validity of using variable-length arrays in C++, with some participants arguing against their use while others suggest alternatives like vectors. The discussion remains unresolved regarding the best practices for handling arrays of variable length in C++.

Contextual Notes

Participants express uncertainty about the status of variable-length arrays in C++ standards and highlight potential issues with array indexing. The discussion also reflects varying levels of familiarity with C++ among participants.

Who May Find This Useful

This discussion may be useful for C++ programmers, particularly those interested in memory management, array handling, and the differences between C and C++ standards.

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;
 

Similar threads

Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 25 ·
Replies
25
Views
3K
Replies
3
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K
Replies
12
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K