Access violation with using structures and arrays without using pointers

0

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?

c++
arrays
struct
visual-studio-2013
access-violation
asked on Stack Overflow Oct 21, 2014 by JoeyChor • edited Oct 21, 2014 by JoeyChor

2 Answers

5

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.

answered on Stack Overflow Oct 21, 2014 by timrau
0

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;
}
answered on Stack Overflow Oct 21, 2014 by Vishal Gupta • edited Oct 27, 2014 by JoeyChor

User contributions licensed under CC BY-SA 3.0