So I'm trying to make this program that takes a struct array in a struct array and assigns a random number from 1-9 to it
struct multiDim
{
int t[16];
};
struct multi
{
multiDim t[16];
};
multi generate()
{
multi m;
srand(time(NULL));
for (int i = 0;i <= 16; i++)
{
for (int I = 0;I <= 16;I++)
{
int ii = rand();
ii = ii % 10;
if (ii <= 9)
{
m.t[i].t[I] = ii;
}
}
}
return m;
}
When I try to compile it using Visual Studio 2013, it causes an error when I try to return m, stating
Unhandled exception at 0x0002609B in ConsoleApplication2.exe: 0xC0000005: Access violation writing location 0x00000007.
The reason I'm using an array in a structure in an array in a structure is because to rather to avoid <std::vector<std::vector<int>>
or some other method. I'm not using any pointers or dereferencing operators, so I'm not sure how it's causing it to throw.
However, on another computer running pocketcpp, I was able to compile and execute it successfully, but only removing the stdafx.h file, as that only applies to the Visual Studio instance. Any reasons why that compiler isn't executing correctly?
The legal index to a 16-element is [0, 15], not [0, 16]. Thus,
for (int i = 0;i <= 16; i++)
should be rewritten into
for (int i = 0; i < 16; i++)
It also applies to the I
loop.
Problem is with the for loop: for (int i = 0;i <= 16; i++)
So use the following code:
struct multiDim
{
int t[16];
};
struct multi
{
multiDim t[16];
};
multi generate()
{
multi m;
// srand(time(NULL));
for (int i = 0;i < 16; i++)
{
for (int I = 0;I < 16;I++)
{
int ii = 100;
ii = ii % 10;
if (ii <= 9)
{
m.t[i].t[I] = ii;
}
}
}
return m;
}
User contributions licensed under CC BY-SA 3.0