+ 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?
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;
}
+ 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.
+ 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.