Reputation: 187
I get an error under "int dArray[size]" saying that size needs to be a constant. Can someone explain what that means exactly?
I want it to be an array of size 4 and output 1, 3, 5, and 7.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int dArray[size];
for (int i = 0; i <= size; i++){
dArray[i] = value;
value + 2;
}
}
int main(){
AllocateArray(4, 1);
}
Solved:
Here is the code that ended up working.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int * Array = new int[size];
for (int i = 0; i < size; i++){
Array[i] = value;
value = value + 2;
}
for (int i = 0; i < size; i++){
cout << Array[i] << endl;
}
return Array;
}
int main(){
int *dArray = AllocateArray(4, 1);
}
Upvotes: 0
Views: 56
Reputation: 84
The size of array should be a known constant in compile time, so that compiler can allocate correct memory for that array on the stack. Remember that such a declare is for stack variable. If you do want dynamic array, try std::vector.
Upvotes: 1
Reputation: 57678
You have to declare the size of an array using numbers, #define or const unsigned int
. Otherwise they are considered variable length arrays.
Example:
const unsigned int MAX_ARRAY_SIZE = 14;
double my_array[MAX_ARRAY_SIZE];
Upvotes: 0
Reputation: 536
C++ requires that the size of arrays are determined at compile-time. As size
is determined at runtime, the compiler complains.
If you are interested in having array-like behaviour with a size unknown at compile-time, then consider using std::vector
.
Upvotes: 2
Reputation: 180424
In int dArray[size]
size is not a constant value. Because of that you are getting that error. What you probably wanted to do was make a new array using a pointer and new like:
int * dArray = new int[size];
Upvotes: 3