简体   繁体   中英

Assigning pointer into pointer array

I have a set of pointers to image block objects. I have a derived class member function that returns a pointer to one of these image blocks, it is a virtual function so I can't change the return type without breaking everything.

Here is what I have so far:

ImageBlock* objArray = static_cast<ImageBlock*>( ::operator new ( sizeof ImageBlock * 256 ) );

for ( int i = 0; i < 256; i++ )
    new (&objArray[i]) ImageBlock(blkh, blkw, 0.0);

for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 16; j++) {
        ImageBlock* temp = getNewBlock(i, j, Image); // getBlock returns ImageBlock*
        objArray[i*16 + j] = *temp;
        delete temp;
    }
}

As you can see this is a terrible solution. I'd like to assign the pointer directly using some pointer arithmetic like so:

for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 16; j++) {
        (objArray+(i*16 + j)) = getNewBlock(i, j, Image);
    }
}

However I get the error expression must be a modifiable lvalue with objArray underlined in red. I know it would work the other way around taking a pointer from the array. I've searched the error and I keep seeing things like "you can't assign to arrays" well it isn't an array in the conventional sense is it? I have a few thoughts on why it won't work but I would like to know for sure. If anyone could offer up a better solution that would be interesting.

Thanks

If you would like to assign pointers, you need to create an array of pointers. What you have is an array of ImageBlock objects, so the solution that you provided, ie

objArray[i*16 + j] = *temp;

is perfectly fine. If you would like to make an array of pointers, you need to declare and use it differently:

ImageBlock** objPtrArray = new ImageBlock*[256];

Now you can make an assignment using square bracket notation:

objPtrArray[i*16 + j] = getNewBlock(i, j, Image);

Of course it is now your responsibility to delete elements of objArray .

A better solution would be to use a vector of smart pointers. This would free you up from the chores of explicit memory management:

vector<unique_ptr<ImageBlock> > objVector(256);
...
objVector.push_back(unique_ptr<ImageBlock>(getNewBlock(i, j, Image)));

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