I already know that a static
storage class allows a local variable to keep on existing on the duration of the program.
What I would like to know why it is needed to declare the digits[3]
array as static. What happens if I don't declare it as static, other than a compiling error.
P.S. I am quite new in handling pointers or memory addresses in C++.
Although I have a bit of an idea on the stack memory allocation regarding scopes in C++.
int* getDigits(int input)
{
const int TEN = 10;
int toStore;
int digits[3]; /* this array (static) */
for (int i = 0; i < 3; ++i)
{
toStore = input % TEN;
digits[i] = toStore;
input = input / TEN;
}
return digits;
}
int main(int argc, char const *argv[])
{
int* ptr;
ptr = getDigits(123);
for (int i = 0; i < 3; ++i)
{
std::cout << *( ptr+i ) << std::endl;
}
return 0;
}