Arrays, C style or the new C++ STL container, are compile time sized. You have to write potentially error-prone code to dynamically set the size at run time.
It is much better, and safer, to use a container such as vector.
Arrays, C style or the new C++ STL container, are compile time sized. You have to write potentially error-prone code to dynamically set the size at run time.
is there short answer why is that?
i know vector, I just wanted to try and figure it on my own but i guess im out of ideas...
#include <iostream>
int main()
{
int* a = NULL; // pointer to int, initialize to nothing.
int n; // size needed for array
std::cin >> n; // read in the size
a = newint[n]; // allocate n ints and save ptr in a.
for (int i = 0; i < n; i++)
{
a[i] = 3 * i + 1; // initialize all elements to zero.
}
//. . . use a as a normal array
for (int i = 0; i < n; i++)
{
std::cout << a[i] << "\t";
}
std::cout << std::endl;
delete [] a; // when done, free memory pointed to by a.
a = nullptr;
return 0;
}
Do you really want to deal with all those memory management details?
After getting a good solid foundation, then learning the details would be more productive.
Bjarne Stroustrup, the guy to created C++, in his book "Programming: Principles and Practices Using C++ (2nd Edition)" introduces vectors in the 4th chapter. He doesn't talk about arrays, as well as free store or heap memory, until chapter 17.