0
votes

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?

2
You know that multidimensional arrays are a thing, yes? int m[16][16]; - cdhowie
Yes, but I just find that having multiple structures containing an integer array is easier when I need to return an multidimensional array. - JoeyChor
How so? If the syntax confuses you then you can just typedef int my_matrix[16][16]; and then use the type my_matrix. - cdhowie
@cdhowie I should've done more research then. Thank you for that line of code - JoeyChor

2 Answers

5
votes

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.

0
votes

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;
}