Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable-sized object may not be initialized c++

Tags:

c++

I understand that this question was asked before but I don't get why it doesn't work in my case

void calc(vector<char> zodis1, vector<char> zodis2, vector<char> zodisAts,int zo1,int zo2,int zoA)
{
   int i,u=0;

   int zod1[zo1]=0;
   int zod2[zo2]=0;
   int zodA[zoA]=0; 
}

All 3 of zod1, zod2, zoA gives me error: variable-sized object may not be initialized c++ But compiler should know the meaning of zo before initialization cause cout<<zo1; works and print out the meaning

So whats the problem?

like image 750
user3102621 Avatar asked May 20 '14 04:05

user3102621


1 Answers

You can declare an array only with constant size, which can be deduced at compile time. zo1,zo2 and zoA are variables, and the values can be known only at runtime.

To elaborate, when you allocate memory on the stack, the size must be known at compile time. Since the arrays are local to the method, they will be placed on the stack. You can either use constant value, or allocate memory in the heap using new, and deallocate when done using delete, like

int* zod1 = new int[zo1];
//.... other code


delete[] zod1;

But you can use vector instead of array here also, and vector will take care of allocation on the heap.

As a side note, you should not pass vector by value, as the whole vector will be copied and passed as argument, and no change will be visible at the caller side. Use vector<char>& zodis1 instead.

like image 152
Rakib Avatar answered Oct 28 '22 00:10

Rakib