简体   繁体   English

对对象数组的C ++访问冲突

[英]C++ access violation to array of objects

I'm a newbie in C++, and I try to create an array of objects. 我是C ++的新手,并且尝试创建对象数组。 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. 在我= 5的周期中,我遇到访问冲突。 sizeof(CSimple) is 8 (there's only one int field there) if it matters sizeof(CSimple)为8(那里只有一个int字段)

Replace the line within the for-loop with data[i] = CSimple(rand() % 10000) . data[i] = CSimple(rand() % 10000)替换for循环中的行。 Much more readabale, isn't it? 更多readabale,不是吗?

The reason your code failed is because data + i does not increment data by i bytes but by i CSimple 's. 您的代码失败的原因是因为data + i不会使数据按i字节递增,而是按i CSimple Say, if CSimple is four bytes long, then data + i * sizeof(CSimple) would increment data by 16 bytes instead of 4. 假设,如果CSimple为四个字节长,那么data + i * sizeof(CSimple)将使数据增加16个字节,而不是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) );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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