Function argument as array size

Hi,

I made a function like follows:
1
2
3
4
5
6
void foo(const double va, const int q) {
   int qaa[q];
   ......

   return;
}

However, the compiler indicates allocator cannot allocate an array of constant size 0...
Could someone please tell me why, and how can I use the argument "q" to fix the size of array "qaa"?
Thanks a lot!
So far as I've tried, this may not be possible.
But what you could do is int qaa[/*Max Here*/] and use a selected portion of that array.
Hope this helps.
Last edited on
If you want to do this, use dynamic allocation.
http://cplusplus.com/doc/tutorial/dynamic/
Thanks for your reply. Do you mean to define a big enough size of array "qaa" to make sure that it will not have problem of size?
I think he meant more along the lines of making the array "qaa" dynamically allocated. i.e Make it a pointer to the address of "qaa"

so int *qaa = new int[SIZE];

This is because normal arrays need to have a specific size before the program runs so that the compiler can allocate that much memory for each array. But since you will be specifying the memory during run time, you need to have a dynamically allocated array.
Did you read the tutorial Zhuge linked?

In the first few lines the tutorial gives the following example:
1
2
int * bobby;
bobby = new int [5]; 


Unlike what you attemtped, you can use a variable for the array size.
1
2
int * qaa;
qaa = new int [q]; 



In C++ it's written this way:

1
2
3
4
5
6
void foo(const double va, const int q) {
   std::vector<int> qaa(q);
   ......

   return;
}
+1 @ Cubbi.

Use containers. Don't manually allocate unless you have to.
Thanks to you all for your answer!
Topic archived. No new replies allowed.