Reputation: 155
int M=7;
int N=6;
int i=0;
int x=N*M;
int val3[x] = {};
for(int i=0;i<x;i++)
{
//some calculations
if (my condition)
{
//if this condition ok, change value of val[i]
}
cout << i << " " << val[i] << endl;
}
I want to initialize a zero array(val)
, I used above codes, but I got an error which says variable size object may not be initialized. is it not possible to initialize zero array? need your help....thanks
Upvotes: 0
Views: 1024
Reputation: 9892
Alternatively to the std::vector suggested above, you could also do:
int M=7;
int N=6;
int x=N*M;
int* val3 = new int[x];
memset(val3, 0, x * sizeof (int));
for (int i = 0; i < x; i++)
{
// ...
}
// ...
delete [] val3;
Upvotes: 0
Reputation: 137770
C++ does not include variable-length arrays; int val3[ x ]
with x
non-constant is a feature of C99. Not all C99 features are part of C++. Try using std::vector
.
#include <vector>
// contains an array of length x, automatically filled with zeroes
std::vector< int > val3( x );
Upvotes: 4
Reputation: 131789
int val3[x] = {};
C++ doesn't allow arrays to be initialized with a variable that isn't a compile-time constant. Use a const int
for all the variables (except i
).
Btw, you don't use that first int i
(outside the loop).
Upvotes: 3