Function argument as array size

Feb 22, 2013 at 12:47am
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!
Feb 22, 2013 at 1:10am
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 Feb 22, 2013 at 1:10am
Feb 22, 2013 at 1:14am
If you want to do this, use dynamic allocation.
http://cplusplus.com/doc/tutorial/dynamic/
Feb 22, 2013 at 1:15am
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?
Feb 22, 2013 at 2:06am
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.
Feb 22, 2013 at 2:07am
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]; 



Feb 22, 2013 at 2:38am
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;
}
Feb 22, 2013 at 2:54am
+1 @ Cubbi.

Use containers. Don't manually allocate unless you have to.
Feb 22, 2013 at 7:51am
Thanks to you all for your answer!
Topic archived. No new replies allowed.