int fn(int n)
{
const int z = n;
int a[z], i;
i = 2;
for (int j = 0; j <= n - 1; j++) a[j] = 1;
do
{
a[i] = a[i-1] + a[i-2];
i++;
} while (i < n);
return a[n - 1];
}
I made this function in order to get the n number of the fibonacci succession. But when I define the array ( a ), the visual studio warns me that the array is not defined with a constant value even if I define z as a constant integer.
How can I define an array of n variables?
Thanks for your attention mates.
visual studio warns me that the array is not defined with a constant value
In C++, an array dimension must be known at compile time. In your code z, is not known at compile time since it is derived from an argument. Your const modifier only says that you won't modify z. It does not say that z is known at compile time.
To create a variable sized array, you must use new
int *a = newint[z];
Don't forget to delete a, otherwise you will have a memory leak.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Use a vector, you can access it in the same way you would a built-in array, it will automatically release the memory when it goes out of scope so you can be sure you won't leak any memory.
Don't forget to delete[] a, otherwise you will have a memory leak.
The delete function (or is it an operator--I don't remember) is used for dynamically allocated objects, while the delete[] function is used for dynamically allocated arrays of objects.