Hello :)
i'm trying to make an integer array of an unknown size with unknown elements
and so fare have come up with the following code. but i keep running into errors... can someone please explain to me what i am doing wrong and how to go about doing it some other way? thank you :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsignedint) time (0));
int a = 1+(rand() % 20); // a is a random number between 1 and 20
int arr[a]; // declaring array of random size
for (int b=0; b<a; b++) // declaring random elements
{
arr[b] = 1+(rand() % 100);
}
int tot = sizeof( arr ) / sizeof( int ); // getting length of array
cout << tot;
}
You can't create an array with a size that is not known at compilation time.
1 2 3 4 5 6 7 8
///WARNING : CODE WILL NOT COMPILE!! THIS IS EXAMPLE OF BAD CODE
//code...
int a;
std::cout<<"Please tell us the length of an array: ";
std::cin>> a;
int BadArray[a];//Error! You can't create an array which size is unknown at compilation time!
If you want to create an array of size that is unknown at compilation time(e.g. user will input array's size), you must use dynamic data allocation:
1 2 3 4 5 6 7 8 9
//code...
int a;
std::cout<<"Please tell us the length of an array: ";
std::cin>> a;
int* array = newint[a];
//code...
delete[] array;
You may want to search for "dynamic arrays" and general idea of operator new and delete.