I want to declare an array of integer arrays of variable length. I thought it must be possible as follows:
int* opt[59];
opt[1] = {1,7,11,0};
opt[2] = {2,7,11,0};
......
opt[58] = {6,9,12,13,15,17,0};
but this causes a compilation error.
What's wrong?
You can't use {} to assign values to an array unless you do it on the declaration line. So this is valid:
int opt[]={6,32,58,324,7};
But this is not:
int opt[5];
opt={25,67,8,3,36};
Since you want your subarrays to be of variable length, you need to allocate the memory yourself for each subarray, and assign the values in each subarray individually.
> int opt[59][7] =
> { 1, 7,11, 0, 0, 0, 0, 2, 7,11, 0, 0, 0, 0, ....
If you're going to bite the bullet and just allocate the space depending on the maximum length of a row, then you'll find this useful for eliminating a lot of zeros (and a lot of counting)
Code:
int opt[59][7] ={
{ 1, 7, 11 }, // compiler adds 4 zeros for you
{ 2, 7, 11, 12 }, // compiler adds 3 zeros for you
};
This is extra useful if you later decide that 7 isn't enough.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.