Define array of n variables


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.
Because z is not always a constant value. z may change depending on n.
The only way is to use dynamic memory allocation.
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 = new int[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.



closed account (LA48b7Xj)
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.

1
2
3
4
5
6
7
8
9
10
#include <vector>

int fn(int n)
{
	std::vector<int> a(n);	

	//code 
		
	return a[n - 1];
}

Following up on @AbstractAnon's post,

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.
Thanks, the function now works perfectly using vectors.


#include <vector>

int serie(int n)
{
std::vector<int> a(n);
int 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];
}
Topic archived. No new replies allowed.