+ 1

Can you not declare the size of an Array and yet...?

So is it possible to not declare the size of an Array and leave it blank myArray[]; then cin the value later or say int x=4 then myArray[x] for myArray to be 5 in size?

9th Nov 2017, 1:44 AM
Rezwan
Rezwan - avatar
4 Answers
+ 4
Yes; #include <iostream> using namespace std; int main() { int *myArray = NULL; int x; cin>>x; myArray = new int[x]; for(int i = 0; i < x; ++i) { myArray[i] = (i+1)*5; } for(int i = 0; i < x; ++i) { cout << myArray[i] << endl; } delete [] myArray; return 0; }
9th Nov 2017, 2:10 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
@Rezwan Hossain Actually, your second approach will not assign your array with the required size. It will assign the array with a random garbage value, usually greater than the size people usually enter. This is because arrays need their size the moment they are initialized, and x will initially have a garbage value, so the array uses the garbage value for its size. You may try printing (sizeof(arr)/sizeof(arr[i]) to verify the same.
9th Nov 2017, 6:09 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
also i just figured out myArray[]{}; //also works as declaration without any size or value which you can later fill OR myArray[x]{}; cin >> x; //to give it a size later.
9th Nov 2017, 2:21 AM
Rezwan
Rezwan - avatar