简体   繁体   中英

C++ access violation to array of objects

I'm a newbie in C++, and I try to create an array of objects. I use a code like

const int SORT_SIZE = 20;

int _tmain(int argc, _TCHAR* argv[])
{
    CSimple * data;
    data = new CSimple[SORT_SIZE];

    for(int i = 0; i < SORT_SIZE; i++)
    {
/*Access violation here*/   *(data + i * (sizeof(CSimple))) = *(new CSimple(rand() % 10000));
    }

and in my cycle on i = 5 i get access violation. sizeof(CSimple) is 8 (there's only one int field there) if it matters

Replace the line within the for-loop with data[i] = CSimple(rand() % 10000) . Much more readabale, isn't it?

The reason your code failed is because data + i does not increment data by i bytes but by i CSimple 's. Say, if CSimple is four bytes long, then data + i * sizeof(CSimple) would increment data by 16 bytes instead of 4.

As a newbie, why don't you make your life easier and use types that do the hard work for you automatically?

#include <vector>

const int SORT_SIZE = 20;

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<CSimple> data;

    for(int i = 0; i < SORT_SIZE; i++)
    {
        data.push_back( CSimple(rand() % 10000) );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM