Reputation: 31
Currently, C++ only allows declaring arrays with length as integers. Is there any way to get around it? I am trying to create a program that generates an array that can potentially reach thousands or even millions in length depending on input, but array declaration limiting to integer-only length is holding me back.
Comment Basically, supposing that I want to create a 2d array with 5 rows and 500,000 columns, I get a segmentation fault.
Upvotes: 1
Views: 1085
Reputation: 4273
The prototype for std::array
is
template<class T, std::size_t N> struct array;
According to https://en.cppreference.com/w/cpp/types/size_t,
std::size_t
can store the maximum size of a theoretically possible object of any type (including array). A type whose size cannot be represented bystd::size_t
is ill-formed (since C++14)
(emphasis mine)
So C++, by definition, cannot express the concept of an object whose size is larger than a std::size_t
.
Fortunately, on most platforms std::size_t
is going to be 32 bits at a minimum, meaning it can reach not only millions but billions. And if you're on a platform where it's smaller than that then presumably your hardware isn't physically capable of storing larger objects anyway.
UPDATE: In the comments you add
Sorry, I ought to have been more specific. Basically, supposing that I want to create a 2d array with 5 rows and 500,000 columns, I get a segmentation fault.
If the problem here were a limitation of the language, you would get a compiler error, not a runtime error.
Since you're getting a runtime error, the problem is with your platform, not the language. In this particular case, the "problem" is that it doesn't give you enough stack space to support multi-megabyte objects in a stack frame. (This is a pretty sensible limitation, if you ask me.) Instead, you'll want to allocate your data on the heap.
I could hand you some code that would just make your problem go away for now, but what you really need to do is read about the stack and heap and understand what they are and how to use them.
Upvotes: 9
Reputation: 27
std::vector
is a better choice. You only need push_back
or emplace_back
to add element into it.
More details: http://www.cplusplus.com/reference/vector/vector/
Upvotes: 0
Reputation: 19
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
int *arr = new int[n]; // dynamic declaration of variable length array
for(int i = 0; i < n; ++i)
std::cin >> arr[i]; // read array elements
return 0;
}
EDIT: For 2d array
#include <iostream>
int main() {
int **arr;
int r, c;
std::cin >> r >> c;
// Create an array of row heads
arr = new int *[r];
// Create an 2d array
for (int i = 0; i < r; ++i) arr[i] = new int[c];
// read input in 2d array
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) std::cin >> arr[i][j];
// print 2d array
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) std::cout << arr[i][j] << ' ';
return 0;
}
Upvotes: 1